c++的文件读写
时间: 2023-09-01 08:08:21 浏览: 46
C++中文件读写可以使用标准库中的fstream头文件中的ifstream和ofstream类。
ifstream类用于从文件读取数据,ofstream类用于向文件写入数据,同时也可以使用fstream类同时进行读写操作。
下面是一个简单的示例:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// 打开文件
ofstream outfile("example.txt");
// 写入数据
outfile << "Hello, World!" << endl;
// 关闭文件
outfile.close();
// 打开文件
ifstream infile("example.txt");
// 读取数据
string line;
getline(infile, line);
cout << line << endl;
// 关闭文件
infile.close();
return 0;
}
```
在这个例子中,我们首先使用`ofstream`打开一个名为`example.txt`的文件,并向其中写入了一行字符串。然后关闭文件。接下来,我们使用`ifstream`打开同一个文件,并从中读取了一行字符串。最后关闭文件。
需要注意的是,在使用`ofstream`或`ifstream`打开文件时,需要指定文件名和打开模式。例如,`ofstream outfile("example.txt")`中的`example.txt`是文件名,而`ofstream`则是打开模式,表示以写入模式打开文件。其他常用的打开模式包括`ifstream`(读取模式)、`fstream`(读写模式)、`app`(在文件末尾追加数据)等。