c++文件读写
时间: 2023-07-23 11:21:56 浏览: 48
在 C++ 中,可以使用 `fstream` 类来进行文件读写操作。`fstream` 类是一个通用的文件输入输出流类,可以用于读取和写入文本文件或二进制文件。
下面是一个简单的示例代码,演示如何使用 `fstream` 类读写文本文件:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// 写入文件
ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, World!" << endl;
outFile << "This is an example file." << endl;
outFile.close();
}
else {
cerr << "Failed to open file." << endl;
return 1;
}
// 读取文件
ifstream inFile("example.txt");
if (inFile.is_open()) {
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}
else {
cerr << "Failed to open file." << endl;
return 1;
}
return 0;
}
```
在这个示例代码中,我们首先使用 `ofstream` 类创建一个文件输出流 `outFile`,然后使用 `outFile` 对象的 `<<` 运算符将数据写入文件。在写入完成后,我们使用 `outFile.close()` 函数关闭文件。
接下来,我们使用 `ifstream` 类创建一个文件输入流 `inFile`,然后使用 `inFile` 对象的 `getline()` 函数逐行读取文件中的数据,并将每行数据输出到控制台。在读取完成后,我们使用 `inFile.close()` 函数关闭文件。
需要注意的是,在使用 `fstream` 类进行文件读写时,需要确保文件被成功打开。如果文件打开失败,可以使用 `cerr` 对象输出错误信息,并使用 `return` 语句终止程序。另外,在写入文件时,需要使用 `ofstream` 类;在读取文件时,需要使用 `ifstream` 类。如果需要同时进行文件读写,可以使用 `fstream` 类。