File Handling
Using C++ we can handle files present in the local drive of the system. This function of handling files using C++ is known as File Handling. We can open a file to read, write, append using fstream. When you open a file for reading or writing, it becomes stream. Stream is a sequence of bytes traveling from a source to a destination over a communication path.
Mode Flag | Description |
---|---|
ios::out | Open a file for writing |
ios::app | Append mode. All output to that file to be appended to the end |
ios::in | Open a file for reading |
ios::ate | Open a file for output and move the read/write control to the end of the file |
ios::trunc | If the file already exists, its contents will be truncated before opening the file |
CODE
EG 1 . Reading, Appending, Writing in a file using C++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
    fstream myFile;
    //----- 1. Writing -----
    myFile.open("CodersCapsule.txt",ios::out);
    myFile << "This is file handling" << endl;
    myFile.close();
    //----- 2. Appending -----
    myFile.open("CodersCapsule.txt",ios::app);
    myFile << "Iam appending this line" << endl;
    myFile.close();
    //----- 3. Reading -----
    myFile.open("CodersCapsule.txt", ios::in);
    string line;
    while (getline(myFile,line)) {
        cout << line << endl;
    }
}
(Click Here, For more exercises)