c++:C++用fstream读写文件

fstream介绍

(1)fstream是C++标准库中面向对象库的一个,用于操作流式文件

(2)fstream本质上是一个class,提供file操作的一众方法

可以直接查看

c 复制代码
man --version
man 2.10.2

在线查看:
https://cplusplus.com/reference/#google_vignette

https://zh.cppreference.com/w/首页

需要添加头文件:

c 复制代码
#include <fstream>
#include <cstring> // 用于strlen函数
c 复制代码
// 打开文件进行读写和追加
  fstream file;
  file.open("example.txt", ios::in | ios::out | ios::app);

  // 检查文件是否成功打开
  if (!file.is_open()) {
    cerr << "Unable to open file example.txt" << endl;
    return 1;  // 返回错误代码
  }

  // 写入文件内容
  file << "Appending some text to the file." << endl;

  // 将文件指针移动到文件开头以进行读取
  file.seekg(0);

  // 读取文件内容并输出
  string line;
  while (getline(file, line)) {
    cout << line << endl;
  }

  // 关闭文件
  file.close();
  return 0;

open:

c 复制代码
  // 打开文件进行读写和追加
  fstream file;
  file.open("example.txt", ios::in | ios::out | ios::app);

  // 检查文件是否成功打开
  if (!file.is_open()) {
    cerr << "Unable to open file example.txt" << endl;
    return 1;  // 返回错误代码
  }

  // 写入文件内容
  file << "Appending some text to the file." << endl;
  const char* str = "Hello, World!";
  file.write(str, strlen(str));
  // 使用 write 写入 std::string 对象
  string str1 = "Hello, C++";
  file.write(str1.c_str(), str1.size());
  file << endl;  // 写入换行符以区分不同写入操作
  // 将文件指针移动到文件开头以进行读取
  file.seekg(0);
#if 0
  // 读取文件内容并输出
  string line;
  while (getline(file, line)) {
    cout << line << endl;
  }
#else
  cout << "======================" << endl;
  // 获取文件大小
  file.seekg(0, ios::end);
  streamsize size = file.tellg();
  file.seekg(0, ios::beg);

  // 创建缓冲区并读取文件内容
  char* buffer = new char[size + 1];
  file.read(buffer, size);
  buffer[size] = '\0';  // 添加终止符

  // 输出逐行读取的内容
  char* line1 = strtok(buffer, "\n");
  while (line1 != nullptr) {
    cout << line1 << endl;
    line1 = strtok(nullptr, "\n");//用于指定分割字符串的分隔符集合
  }
  // 清理并关闭文件
  delete[] buffer;
#endif
  // 关闭文件
  file.close();
  return 0;

总结

可以使用fstream读写文件

学习记录,侵权联系删除。

来源:朱老师物联网大课堂

相关推荐
小汉堡编程3 小时前
数据结构——vector数组c++(超详细)
数据结构·c++
weixin_472339465 小时前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
枯萎穿心攻击6 小时前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
Eiceblue7 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
tan180°8 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
m0_555762908 小时前
Matlab 频谱分析 (Spectral Analysis)
开发语言·matlab
浪裡遊9 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
彭祥.9 小时前
Jetson边缘计算主板:Ubuntu 环境配置 CUDA 与 cudNN 推理环境 + OpenCV 与 C++ 进行目标分类
c++·opencv·分类
lzb_kkk9 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
好开心啊没烦恼10 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy