Read and write (fstream)

Objects of the class fstream are used for general file operations. With this class it is possible to write to and read from files.

Open a file

fstream myFile;
myFile.open(filename, ios::out | ios::in);

Example: write to file

#include <fstream>
#include <iostream>
using namespace std;

int main() {
    string str;
    fstream myFile;
    myFile.open("textfile.txt", ios::out);
    if (myFile.is_open()) {
        myFile << "New line to text file" << endl;
        myFile.close();
    } else {
        cout << "Unable to open text file";
    }

    return 0;
}
Output
[textfile.txt]
New line to text file

Example: read from file

#include &lt;fstream&gt;
#include &lt;iostream&gt;
using namespace std;

int main() {
    string str;
    fstream myFile;
    myFile.open("Documents/website/codevisionz/textfile.txt", ios::in);
    if (myFile.is_open()) {
        while (!myFile.eof()) {
            getline(myFile, str);
            cout << str << endl;
        }
        myFile.close();
    } else {
        cout << "Unable to open text file";
    }

    return 0;
}
Output
New line to text file