18 Jul C++ File Handling
To read and write to a file in C+, use the fstream library. The <iostream> and <fstream> header files are used to work on the fstream. With that, the following are the classes of the fstream to work on files in C++:

Create a File
To create a file in C++, include the following header files:
#include <iostream> #include <fstream>
The following code snippet displays how to create a file myfile.txt:
ofstream DemoFile("E:\Amit\myfile.txt");
The file myfile.txt gets created at the location. The file is empty since we did not add any text to it:

Now, let us see how to create and write a file. We will continue the above example.
Create and Write to a File
To create and write a file in C++, include the following header files as we saw above:
#include <iostream> #include <fstream>
To write, use the insertion operator i.e., << as shown below:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create a File
ofstream DemoFile("E:\Amit\myfile.txt");
// Write to the File
DemoFile << "This is a demo text written to a file";
// Close the File
DemoFile.close()
}
The myfile.txt file is now having the following text as shown below:

Always remember to close an opened file using the close() method.
Read a File
To read a file in C++, use the fstream or ifstream class. Always remember to close an opened file using the close() method.
We will read the above myfile.txt with the following text:

Let us now see the example to read the above file i.e., myfile.txt that already exists:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
// Create a File
ofstream DemoFile("E:\Amit\myfile.txt");
// Write to the File
DemoFile << "This is a demo text written to a file";
// Close the File
DemoFile.close()
// Create a string
string str;
// Read the file
ifstream DemoFile("E:\Amit\myfile.txt");
// Read the file linne by line
while (getline (DemoFile, str)) {
// Display the text from myfile.txt
cout << str;
}
// Close the file
DemoFile.close();
}
Output
This is a demo text written to a file.
No Comments