doc/notebook/docs/C++/2.fstream.md

87 lines
2.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

1. `std::ifstream`: 用于从文件中读取数据的输入流对象。常用的成员函数包括:
- `open(const char* filename)`: 打开指定文件名的文件。
- `close()`: 关闭文件。
- `is_open()`: 判断文件是否已经打开。
- `good()`: 判断文件流状态是否良好。
```cpp
#include <fstream>
#include <iostream>
int main() {
std::ifstream inputFile;
inputFile.open("input.txt");
if (inputFile.is_open()) {
std::cout << "File opened successfully." << std::endl;
// 读取文件内容
std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl;
}
inputFile.close();
} else {
std::cerr << "Unable to open file." << std::endl;
}
return 0;
}
```
2. `std::ofstream`: 用于向文件中写入数据的输出流对象常用的成员函数包括
- `open(const char* filename)`: 创建或打开指定文件名的文件
- `close()`: 关闭文件
- `is_open()`: 判断文件是否已经打开
- `good()`: 判断文件流状态是否良好
```cpp
#include <fstream>
#include <iostream>
int main() {
std::ofstream outputFile;
outputFile.open("output.txt");
if (outputFile.is_open()) {
std::cout << "File opened successfully." << std::endl;
// 写入数据到文件
outputFile << "Hello, world!" << std::endl;
outputFile << 42 << std::endl;
outputFile.close();
} else {
std::cerr << "Unable to open file." << std::endl;
}
return 0;
}
```
3. `std::fstream`: 同时支持读写操作的文件流对象常用的成员函数包括
- `open(const char* filename, std::ios_base::openmode mode)`: 打开指定文件名的文件并指定打开模式例如`std::ios::in`表示读取模式`std::ios::out`表示写入模式)。
- `close()`: 关闭文件
- `is_open()`: 判断文件是否已经打开
- `good()`: 判断文件流状态是否良好
```cpp
#include <fstream>
#include <iostream>
int main() {
std::fstream file;
file.open("data.txt", std::ios::out | std::ios::app);
if (file.is_open()) {
std::cout << "File opened successfully." << std::endl;
// 写入数据到文件
file << "Appended line." << std::endl;
file.close();
} else {
std::cerr << "Unable to open file." << std::endl;
}
return 0;
}
```
这些函数和对象使得在C++中进行文件输入输出操作变得简单和方便