fstream(c++)

#include <fstream> 是 C++ 中用于进行文件输入输出(I/O)操作的标准头文件,它提供了对文件读写的支持,主要包括三个类:


一、<fstream> 中的三个主要类

类名功能继承自
ifstream用于读取文件istream
ofstream用于写入文件ostream
fstream用于读写文件iostream

二、常用方法详解

1. 文件打开方式(可用作 open() 第二个参数)

模式名含义
ios::in以读模式打开
ios::out以写模式打开(默认覆盖)
ios::app追加写入到文件末尾
ios::ate打开文件并移动到文件尾部
ios::trunc如果文件存在,清空内容
ios::binary以二进制模式打开

可以用 | 组合多种模式,例如:ios::in | ios::out


2. 常用成员函数

函数说明
open(filename, mode)打开文件
is_open()检查文件是否成功打开
close()关闭文件
<<>> 运算符向文件写入/从文件读取
getline(istream, str)读取整行
eof()判断是否到达文件末尾

三、读写文件示例

示例 1:写入文件(使用 ofstream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <fstream>
#include <iostream>

int main() {
std::ofstream outfile("example.txt"); // 打开文件,如果不存在则创建

if (!outfile.is_open()) {
std::cerr << "无法打开文件进行写入\n";
return 1;
}

outfile << "Hello, world!" << std::endl;
outfile << "写入第二行数据" << std::endl;

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

示例 2:读取文件(使用 ifstream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <fstream>
#include <iostream>
#include <string>

int main() {
std::ifstream infile("example.txt"); // 打开文件

if (!infile.is_open()) {
std::cerr << "无法打开文件进行读取\n";
return 1;
}

std::string line;
while (std::getline(infile, line)) { // 一行一行读取
std::cout << line << std::endl;
}

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

示例 3:读写文件(使用 fstream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <fstream>
#include <iostream>
#include <string>

int main() {
std::fstream file("example.txt", std::ios::in | std::ios::out);

if (!file.is_open()) {
std::cerr << "无法打开文件\n";
return 1;
}

std::string data;
file >> data; // 读取一个单词
std::cout << "读取的数据:" << data << std::endl;

file.clear(); // 清除 EOF 状态
file.seekp(0, std::ios::end); // 移动写入指针到末尾

file << "\n追加一行数据";

file.close();
return 0;
}

四、注意事项

  1. 文件操作完成后应当调用 close() 关闭文件。
  2. 文件路径可以是相对路径或绝对路径。
  3. 在打开文件前检查文件是否存在有助于避免错误。
  4. fstream 可以同时读写,但要注意 seekgseekp 调整位置。