C++ <fstream>
标准库中文件输入输出操作的类,提供了读写文件方法。fstream
是iostream
库的一部分,支持文本和二进制文件的读写。fstream
类是iostream
库中的一个类,它继承自istream
和ostream
类。
<fstream>
提供了三个主要的类:ifstream
(用于从文件读取数据)、ofstream
(用于向文件写入数据)和fstream
(同时支持读写操作)。
fstream
的基本语法:
#include <fstream>
int main() {
std::fstream file; // 创建fstream对象
file.open("filename", mode); // 打开文件
// 进行文件操作
file.close(); // 关闭文件
return 0;
}
std::ios::in
:以输入模式打开文件。std::ios::out
:以输出模式打开文件。std::ios::app
:以追加模式打开文件。std::ios::ate
:打开文件并定位到文件末尾。std::ios::trunc
:打开文件并截断文件,即清空文件内容。
打开文件:
打开一个文件,这可以通过创建ifstream
、ofstream
或fstream
对象,并调用其open
方法来实现。也可以在构造这些对象时直接传入文件名来打开文件。
std::fstream file("readwrite.txt", std::ios::in | std::ios::out); // 打开文件以读写
或
std::fstream file;
file.open("example.txt", std::ios::out); // 以输出模式打开文件
读取文件:
使用ifstream
对象,可以从文件中读取数据。常用的读取方法包括>>
运算符(用于读取格式化的数据)和getline()
函数(用于读取一行文本)。
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl; // 输出读取的每一行
}
写入文件:
file << "Appending this line to the file." << std::endl; // 向文件中写入
关闭文件:
file.close();
示例代码:
#include <fstream>
#include <iostream>
int main() {
std::fstream file;
file.open("example.txt", std::ios::app); // 以追加模式打开文件
if (!file) {
std::cerr << "Unable to open file!" << std::endl;
return 1; // 文件打开失败
}
file << "Appending this line to the file." << std::endl; // 追加文本
file.close(); // 关闭文件
return 0;
}