c++文件打开方式
时间: 2023-07-23 09:16:31 浏览: 73
在 C++ 中,可以使用文件流来打开和操作文件。文件流分为输入流和输出流,分别用于读取文件和写入文件。常用的文件打开方式有以下三种:
1. 以读取方式打开文件:
```c++
#include <fstream>
std::ifstream infile("input.txt"); // 打开 input.txt 文件,以读取方式打开
```
2. 以写入方式打开文件:
```c++
#include <fstream>
std::ofstream outfile("output.txt"); // 打开 output.txt 文件,以写入方式打开
```
3. 以读写方式打开文件:
```c++
#include <fstream>
std::fstream file("data.txt", std::ios::in | std::ios::out); // 打开 data.txt 文件,以读写方式打开
```
其中,`infile` 和 `outfile` 分别表示输入流和输出流,`file` 表示读写流。`ios` 是 C++ 中的输入输出状态标志,`std::ios::in` 表示以读取方式打开文件,`std::ios::out` 表示以写入方式打开文件,`std::ios::in | std::ios::out` 表示以读写方式打开文件。
打开文件后,可以使用文件流进行读取和写入操作,例如:
```c++
#include <fstream>
#include <iostream>
int main() {
std::ifstream infile("input.txt"); // 打开 input.txt 文件,以读取方式打开
if (!infile.is_open()) {
std::cout << "文件打开失败!" << std::endl;
return -1;
}
int a, b;
infile >> a >> b; // 从文件中读取两个整数
std::cout << "a = " << a << ", b = " << b << std::endl;
infile.close(); // 关闭文件
return 0;
}
```
在读取文件时,需要先判断文件是否打开成功,可以使用 `is_open()` 函数判断。关闭文件时,可以使用 `close()` 函数关闭文件。