Cpp Libs Fstream
# C++ File Input/Output with ``
In C++, the `` header provides the standard library classes for performing input and output operations on files. It offers a robust, stream-oriented approach to reading from and writing to files on disk.
The `` library is part of the larger C++ I/O stream hierarchy. It supports both text and binary file operations, inheriting functionality from `std::istream` (for input) and `std::ostream` (for output).
---
## The `` Class Hierarchy
The `` header defines three primary classes:
* **`std::ifstream`**: Input file stream. Used exclusively for reading data from files (inherits from `std::istream`).
* **`std::ofstream`**: Output file stream. Used exclusively for writing data to files (inherits from `std::ostream`).
* **`std::fstream`**: Bidirectional file stream. Can be used for both reading from and writing to files (inherits from `std::iostream`).
---
## Syntax and File Open Modes
To perform file operations, you instantiate a stream object, open the target file with specific access modes, perform the read/write operations, and close the file.
### Basic Syntax
```cpp
#include
int main() {
std::fstream file; // Create an fstream object
file.open("filename.txt", mode); // Open the file with a specific mode
// ... Perform file operations ...
file.close(); // Close the file to free system resources
return 0;
}
```
### File Open Modes
The `mode` parameter determines how the file is opened. These flags are defined in the `std::ios` class and can be combined using the bitwise OR operator (`|`):
| Mode Flag | Description |
| :--- | :--- |
| `std::ios::in` | Opens the file for reading (input). |
| `std::ios::out` | Opens the file for writing (output). Discards existing content unless combined with other flags. |
| `std::ios::app` | Append mode. All output operations are performed at the end of the file. |
| `std::ios::ate` | "At the end". Opens the file and moves the read/write control pointer to the end of the file. |
| `std::ios::trunc` | Truncate mode. If the file already exists, its contents are discarded (cleared) upon opening. |
| `std::ios::binary` | Opens the file in binary mode (instead of text mode). |
---
## Code Examples
### 1. Writing to a Text File
The following example demonstrates how to create a new file (or overwrite an existing one) and write a line of text to it using the stream insertion operator (`<<`).
```cpp
#include
#include
int main() {
std::fstream file;
// Open the file in output mode
file.open("example.txt", std::ios::out);
// Always check if the file opened successfully
if (!file) {
std::cerr << "Error: Unable to open file for writing!" << std::endl;
return 1;
}
// Write text to the file
file << "Hello, World!" << std::endl;
// Close the file
file.close();
return 0;
}
```
**Output File (`example.txt`):**
```text
Hello, World!
```
---
### 2. Reading from a Text File
This example demonstrates how to open an existing file and read its contents line-by-line using `std::getline`.
```cpp
#include
#include
#include
int main() {
std::fstream file;
// Open the file in input mode
file.open("example.txt", std::ios::in);
// Check if the file exists and can be opened
if (!file) {
std::cerr << "Error: Unable to open file for reading!" << std::endl;
return 1;
}
std::string line;
// Read the file line-by-line until the end of the file (EOF)
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
// Close the file
file.close();
return 0;
}
```
If `example.txt` contains:
```text
Hello, World!
This is a test file.
```
The console output will be:
```text
Hello, World!
This is a test file.
```
---
### 3. Appending Data to an Existing File
To add content to the end of a file without deleting its existing contents, use the `std::ios::app` mode.
```cpp
#include
#include
int main() {
std::fstream file;
// Open the file in append mode
file.open("example.txt", std::ios::app);
if (!file) {
std::cerr << "Error: Unable to open file for appending!" << std::endl;
return 1;
}
// Append a new line of text
file << "Appending this line to the file." << std::endl;
// Close the file
file.close();
return 0;
}
```
If `example.txt` originally contained:
```text
Hello, World!
This is a test file.
```
After running the append program, the file contents will be:
```text
Hello, World!
This is a test file.
Appending this line to the file.
```
---
## Important Considerations
1. **RAII and Automatic Resource Management**:
While calling `.close()` explicitly is good practice, C++ file stream destructors automatically close the file when the stream object goes out of scope.
```cpp
{
std::ofstream outFile("temp.txt");
outFile << "Temporary data";
} // outFile goes out of scope here; the file is automatically closed.
```
2. **Error Checking**:
Always verify that a file opened successfully before reading or writing. You can evaluate the stream object directly in a boolean context (e.g., `if (!file)`) or call `file.is_open()`.
3. **Stream State Flags**:
File streams maintain internal state flags that you can query:
* `good()`: Returns `true` if no error flags are set.
* `eof()`: Returns `true` if the stream has reached the End-Of-File.
* `fail()`: Returns `true` if an input/output operation failed (e.g., format mismatch).
* `bad()`: Returns `true` if a fatal error occurred (e.g., physical disk failure).
YouTip