File Modes in C++
### Introduction
File handling in C++ is performed using the fstream library, which allows reading and writing to files.
C++ provides three main classes for file operations:
- ifstream - For reading from a file.
- ofstream - For writing to a file.
- fstream - For both reading and writing.
### File Modes in C++
File modes determine how a file is opened and accessed. Some commonly used file modes are:
| File Mode | Description |
|-----------|------------|
| ios::in | Opens file for reading (input mode). |
| ios::out | Opens file for writing (output mode). If the file exists, it overwrites the content. |
| ios::app | Opens file in append mode, data is added to the end of the file. |
| ios::ate | Opens file and moves the pointer to the end of the file. |
| ios::trunc | If the file exists, it deletes the contents before writing. |
| ios::binary | Opens file in binary mode instead of text mode. |
### Example Program in C++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Writing to a file
ofstream outFile("data.txt"); // Opens file in default ios::out mode
outFile << "Hello, this is a simple file handling example.\n";
outFile.close(); // Closing the file
// Reading from a file
ifstream inFile("data.txt"); // Opens file in ios::in mode
string line;
while (getline(inFile, line)) {
cout << "File Content: " << line << endl;
}
inFile.close(); // Closing the file
// Appending to a file
ofstream appendFile("data.txt", ios::app); // Opens file in append mode
appendFile << "This is an appended line.\n";
appendFile.close(); // Closing the file
return 0;
}
### Explanation:
1. Writing to a File (ios::out)
- Creates a file data.txt and writes text into it.
2. Reading from a File (ios::in)
- Reads and displays the content of data.txt.
3. Appending to a File (ios::app)
- Adds a new line to the existing file content without erasing it.
### Conclusion
File handling in C++ is essential for storing and retrieving data. Different file modes allow efficient
control over file operations, such as reading, writing, and appending data.