File Modes Cpp
File Modes Cpp
### Introduction
File handling in C++ is performed using the fstream library, which allows reading and writing to files.
File modes determine how a file is opened and accessed. Some commonly used file modes are:
|-----------|------------|
| 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. |
#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
// 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:
- 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.