Skip to content

[C++] Tutorial(5): File Read and Write

Last Updated on 2021-05-06 by Clay

Data is text format can be said to be one of the most basic data forms of computer system. For example, Linux operating system has many settings that are stored in text file for the convenience of users to adjust freely.

In C++, if you want to read or write a file, you need to use ifstream (Input)and ofstream (Output) of fstream library; Or you can use fstream to call different mode of open() function.

We can read the specified text file through the open() function. There are many types of modes:

ModeUsage
ios::inFile reading mode
ios::outFile writing mode
ios::ateRead and write data from the end of the file
ios::appWrite data from the end of the file
ios::truncClear file contents
ios::nocreatIf you open a file that does not exist, an error will be reported
ios::noreplaceIf ate and app are set when opening the existing file, an error will be reported
ios::binaryRead files in binary mode
http://www.cplusplus.com/doc/tutorial/files/

The following is a direct program to demonstrate how to write and read files.


Read and Write the file

Create A New Text File

The following is a simple sample file. A new text file named test.txt is created and the line "Today is a nice day." is written.

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


int main() {
    // Create a new file
    ofstream newFile;
    newFile.open("test.txt");

    // Write to the file
    newFile << "Today is a nice day.";
    newFile.close();

    return 0;
}


or

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


int main() {
    // Create a new file
    fstream newFile;
    newFile.open("test.txt", ios::out | ios::trunc);

    // Write to the file
    newFile << "Today is a nice day.";
    newFile.close();

    return 0;
}




Write to existing text file

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


int main() {
    // Open file
    fstream myFile;
    myFile.open("test.txt", ios::app);

    // Write to the file
    myFile << "\nI want to go to play.";

    // Close file
    myFile.close();

    return 0;
}




Read file

To read the test.txt just created, you can use the following program:

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


int main() {
    // Settings
    string line;

    // Open file
    ifstream myFile;
    myFile.open("test.txt");

    // Print file content
    while (getline(myFile, line)) {
        cout << line << endl;
    }

    // Close file
    myFile.close();

    return 0;
}



Output:

Today is a nice day.
I want to go to play.

References


Read More

Tags:

Leave a Reply