c11 fstream
时间: 2023-11-09 14:03:11 浏览: 69
The `<fstream>` header file in C++ provides support for handling input/output operations on files. It defines three classes: `ifstream`, `ofstream`, and `fstream`, which are used for reading, writing, and both reading and writing a file, respectively.
The `ifstream` class is used for reading from a file, and it inherits from the `istream` class. The `ofstream` class is used for writing to a file, and it inherits from the `ostream` class. The `fstream` class is used for both reading and writing to a file, and it inherits from both `ifstream` and `ofstream`.
To use these classes, you need to include the `<fstream>` header file in your program. Then, you can create an object of the appropriate class, and use its member functions to perform the desired operations on the file.
For example, to read data from a file using `ifstream`, you can create an object of type `ifstream`, open the file using the `open()` member function, read the data using the `>>` operator or the `getline()` function, and then close the file using the `close()` member function.
Here's an example code snippet that reads data from a file named "input.txt":
```
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("input.txt");
if (fin.is_open()) {
string line;
while (getline(fin, line)) {
cout << line << endl;
}
fin.close();
} else {
cout << "Unable to open file!" << endl;
}
return 0;
}
```
This code opens the file "input.txt" using the `ifstream` object `fin`, reads each line using the `getline()` function, and then prints it to the console. If the file cannot be opened, it prints an error message. Finally, it closes the file using the `close()` member function.
阅读全文