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:
1 2 3 4 |
#include <iostream> #include <fstream> |
The following code snippet displays how to create a file myfile.txt:
1 2 3 |
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:
1 2 3 4 |
#include <iostream> #include <fstream> |
To write, use the insertion operator i.e., << as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#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
1 2 3 |
This is a demo text written to a file. |
No Comments