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:
Mode | Usage |
---|---|
ios::in | File reading mode |
ios::out | File writing mode |
ios::ate | Read and write data from the end of the file |
ios::app | Write data from the end of the file |
ios::trunc | Clear file contents |
ios::nocreat | If you open a file that does not exist, an error will be reported |
ios::noreplace | If ate and app are set when opening the existing file, an error will be reported |
ios::binary | Read files in binary mode |
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
- [Linux][C++] How to compile and execute a C++ program
- [C++] Tutorial(1): Data Type
- [C++] Tutorial(2): Arithmetic Expression
- [C++] Tutorial(3): Data Input and Output
- [C++] Tutorial(4): if-else, switch, loop and flow control
- [C++] Tutorial(5): File Read and Write
- [C++] Tutorial(6): Pointer and Reference
- [C++] Tutorial(7): Functions