c++文件的读取和写入
时间: 2023-11-05 13:22:18 浏览: 39
C++中文件的读取和写入可以通过文件流来实现,具体可以使用fstream库中的ifstream和ofstream类来分别进行文件的读取和写入。
以下是一个简单的例子,演示如何读取一个文本文件并输出到控制台:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string filename = "example.txt";
ifstream infile(filename);
if (infile.is_open()) {
string line;
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
} else {
cout << "Unable to open file " << filename << endl;
}
return 0;
}
```
以下是一个简单的例子,演示如何将一些文本写入到一个文件中:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string filename = "example.txt";
ofstream outfile(filename);
if (outfile.is_open()) {
outfile << "Hello World!\n";
outfile << "This is a text file.\n";
outfile.close();
} else {
cout << "Unable to create file " << filename << endl;
}
return 0;
}
```
需要注意的是,当写入文件时,如果文件不存在,则会创建一个新文件。如果文件已经存在,则会删除原有内容并写入新的内容。