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读写文件

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

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

相关推荐
爱吃大芒果几秒前
Flutter 本地存储方案:SharedPreferences、SQFlite 与 Hive
开发语言·javascript·hive·hadoop·flutter·华为·harmonyos
Kelvin_Ngan几秒前
Qt包含QtCharts/QValueAxis时编译报错
开发语言·qt
葱卤山猪1 分钟前
【Qt】心跳检测与粘包处理:打造稳定可靠的TCP Socket通信
开发语言·数据库·qt
a程序小傲4 分钟前
淘宝Java面试被问:Atomic原子类的实现原理
java·开发语言·后端·面试
laocooon5238578867 分钟前
C++中的安全指针(智能指针)
开发语言·c++
咸鱼加辣8 分钟前
【python面试题】LRUCache
开发语言·python
LitchiCheng9 分钟前
WSL2 中 pynput 无法捕获按键输入?
开发语言·python
中年程序员一枚9 分钟前
Python 中处理视频添加 / 替换音频
开发语言·python·音视频
yuuki23323310 分钟前
【C++】模板初阶
java·开发语言·c++
爱吃大芒果11 分钟前
Flutter 路由进阶:命名路由、动态路由与路由守卫实现
开发语言·javascript·flutter·华为·ecmascript