c++文件的读取和写入
时间: 2023-07-02 08:12:19 浏览: 36
在 C++ 中,可以使用标准库中的 fstream 头文件来进行文件的读写操作。
1. 文件的写入:
首先需要创建一个 ofstream 对象,并打开要写入的文件,如下所示:
```c++
#include <fstream>
using namespace std;
int main () {
ofstream outfile;
outfile.open("example.txt");
// 写入内容
outfile << "This is a line.\n";
outfile << "This is another line.\n";
// 关闭文件
outfile.close();
return 0;
}
```
在上面的代码中,我们创建了一个名为 outfile 的 ofstream 对象,并通过 open() 函数打开了名为 "example.txt" 的文件。我们然后向文件中写入了两行内容,最后通过 close() 函数关闭文件。
2. 文件的读取:
同样需要创建一个 ifstream 对象,并打开要读取的文件,如下所示:
```c++
#include <fstream>
#include <iostream>
using namespace std;
int main () {
string line;
ifstream infile ("example.txt");
// 逐行读取文件内容
while (getline(infile, line)) {
cout << line << '\n';
}
// 关闭文件
infile.close();
return 0;
}
```
在上面的代码中,我们创建了一个名为 infile 的 ifstream 对象,并通过 open() 函数打开了名为 "example.txt" 的文件。我们然后使用 getline() 函数逐行读取文件内容,并将其显示在屏幕上。最后通过 close() 函数关闭文件。