如何在c++中使用文件流
时间: 2023-12-09 19:02:36 浏览: 42
在 C++ 中,使用文件流需要包含头文件 `fstream`。常用的文件流有 `ifstream`(输入文件流)和 `ofstream`(输出文件流)。
1. 打开文件:
```c++
#include <fstream>
using namespace std;
int main() {
ifstream infile; // 定义输入文件流对象
infile.open("input.txt"); // 打开名为 input.txt 的文件,如果文件不存在则会创建一个新文件
ofstream outfile; // 定义输出文件流对象
outfile.open("output.txt"); // 打开名为 output.txt 的文件,如果文件不存在则会创建一个新文件
}
```
2. 读取文件内容:
```c++
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream infile; // 定义输入文件流对象
infile.open("input.txt");
string content;
while (getline(infile, content)) { // 按行读取文件内容
cout << content << endl; // 输出每一行的内容
}
infile.close(); // 关闭文件流
}
```
3. 写入文件内容:
```c++
#include <fstream>
using namespace std;
int main() {
ofstream outfile; // 定义输出文件流对象
outfile.open("output.txt");
outfile << "Hello World!" << endl; // 写入一行内容
outfile.close(); // 关闭文件流
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)