c++中如何使用fstream读写文件_C++ fstream文件流读写操作指南

fstream是C++中用于文件读写的类,需包含<fstream>头文件,支持文本和二进制文件的输入输出,结合了ifstream和ofstream功能,通过open函数指定in、out、app等模式打开文件,可用<<或write()写入,用>>或getline()读取。

c++中如何使用fstream读写文件_C++ fstream文件流读写操作指南

在C++中,fstream 是用于文件读写操作的核心类,它位于 fstream 头文件中。通过 fstream 可以方便地对文本和二进制文件进行输入输出操作。它继承自 iostream,并结合了 ifstream(输入)和 ofstream(输出)的功能。

1. 包含头文件并创建文件流对象

使用 fstream 前必须包含对应的头文件:

#include <fstream>

然后声明一个 fstream 对象:

std::fstream file;

也可以在构造时直接打开文件:

立即学习C++免费学习笔记(深入)”;

std::fstream file(“example.txt”, std::ios::in | std::ios::out);

2. 打开文件的常用模式

打开文件时可以指定多种模式,用 std::ios 枚举值控制:

  • std::ios::in – 读取文件
  • std::ios::out – 写入文件(默认会清空内容)
  • std::ios::app – 追加模式,写入内容添加到文件末尾
  • std::ios::ate – 打开后立即定位到文件末尾
  • std::ios::binary – 以二进制方式读写

例如,以读写方式打开文件,若不存在则创建:

file.open(“data.txt”, std::ios::in | std::ios::out | std::ios::app);

如果文件不存在且未指定 out 或 app 模式,open 会失败。

3. 写入文件操作

使用 << 操作符或 write() 函数写入数据。

c++中如何使用fstream读写文件_C++ fstream文件流读写操作指南

Mozart AI

AI音乐生成工具,可以将图片、文字转换为音乐

c++中如何使用fstream读写文件_C++ fstream文件流读写操作指南63

查看详情 c++中如何使用fstream读写文件_C++ fstream文件流读写操作指南

file file

对于二进制写入,使用 write():

int value = 100;
file.write(reinterpret_cast<const char*>(&value), sizeof(value));

4. 读取文件操作

使用 >> 操作符读取格式化数据:

std::string name;
int age;
file >> name >> age;

逐行读取可用 std::getline

std::string line;
while (std::getline(file, line)) {
  std::cout }

二进制读取使用 read():

int data;
file.read(reinterpret_cast<char*>(&data), sizeof(data));

5. 检查状态与关闭文件

操作前后应检查文件是否成功打开或读写正常:

if (!file.is_open()) {
  std::cerr }

if (file.fail()) {
  std::cerr << “读写失败!” << std::endl;
}

使用完成后务必关闭文件:

file.close();

6. 完整示例:读写文本文件

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
  fstream file(“test.txt”, ios::out);
  if (file.is_open()) {
    file << “Hello, C++!” << endl;
    file << “Age: 25” << endl;
    file.close();
  }

  file.open(“test.txt”, ios::in);
  if (file.is_open()) {
    string line;
    while (getline(file, line)) {
      cout << line << endl;
    }
    file.close();
  }
  return 0;
}

这个例子先写入两行文本,再读取并打印出来。

基本上就这些。掌握 open、读写操作、模式选择和状态检查,就能灵活使用 fstream 处理大多数文件任务。注意路径正确、及时关闭文件、避免内存泄漏。对于复杂数据结构,建议配合序列化方法使用。不复杂但容易忽略细节。

app c++ ios String while include 继承 ofstream ifstream fstream 对象 ios

上一篇
下一篇