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:
The following code snippet displays how to create a file 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:
To write, use the insertion operator i.e., << as shown below:
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:
Output
No Comments