C++中的文件操作是程序开发中一个非常重要的部分,尤其在需要处理大量数据或保存程序状态时。fstream
库提供了强大的功能来支持文件的读取、写入和修改。本文将全面解析C++中fstream
类的使用方法,包括其基本概念、常用函数以及实际应用中的注意事项。
fstream
是C++标准库中用于文件流操作的一个类,它继承自iostream
,因此可以像控制台输入输出一样进行文件操作。fstream
主要分为三种类型:
ifstream
:专门用于文件读取。ofstream
:专门用于文件写入。fstream
:既可以用于读取也可以用于写入。这些类都继承自std::ios_base
,所以它们共享许多共同的功能和属性。
要开始文件操作,首先需要创建一个fstream
对象并打开目标文件。文件可以通过以下方式打开:
#include <fstream>
using namespace std;
int main() {
fstream file;
file.open("example.txt", ios::in | ios::out);
if (!file) {
cout << "Error: File not found or cannot be opened." << endl;
return 1;
}
// 文件操作代码...
file.close(); // 关闭文件
return 0;
}
ios::in
:以只读模式打开文件。ios::out
:以写入模式打开文件,如果文件不存在则创建新文件。ios::app
:以追加模式打开文件,所有写入都会添加到文件末尾。ios::binary
:以二进制模式打开文件。读取文件内容可以通过多种方式进行,如逐字符读取、逐行读取等。
char ch;
while (file.get(ch)) {
cout << ch;
}
string line;
while (getline(file, line)) {
cout << line << endl;
}
写入文件与标准输出类似,可以直接使用插入运算符<<
。
file << "Hello, world!" << endl;
有时候需要对文件指针进行控制,例如返回文件开头或跳过某些字节。这可以通过seekg
(获取位置)和seekp
(设置位置)来实现。
// 返回文件开头
file.seekg(0, ios::beg);
// 跳过前10个字节
file.seekg(10, ios::beg);
假设我们需要编写一个简单的程序来复制文本文件的内容。
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream inFile("source.txt");
ofstream outFile("destination.txt");
if (!inFile || !outFile) {
cerr << "Cannot open file(s)" << endl;
return 1;
}
char ch;
while (inFile.get(ch)) {
outFile.put(ch);
}
inFile.close();
outFile.close();
return 0;
}