Text files

Writing on text files

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

int main() {
    ofstream myTextFile("textfile.txt");
    if (myTextFile.is_open()) {
        myTextFile << "First line in text file" << endl;
        myTextFile << "Second line in text file\n";
        myTextFile << "Third line in text file";
        myTextFile.close();
    } else {
        cout << "Unable to open text file!";
    }

    return 0;
}
Output
First line in text file
Second line in text file
Third line in text file

Reading from text files

To read lines of text with spaces from files, the element function getline() is used. A pointer to char is passed as the first parameter.

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

int main() {
    string str;
    ifstream myFile("textfile.txt");
    if (myFile.is_open()) {
        while (getline(myFile, str)) {
            cout << str << '\n';
        }
        myFile.close();
    } else {
        cout << "Unable to open textfile";
    }
        
    return 0;
}
Output
First line in text file
Second line in text file
Third line in text file