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++:

C++ File Handling

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:
Create a file in C++

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:
Write to a File in Cplusplus

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:

Read a file in cpluspus

Let us now see the example to read the above file i.e., myfile.txt that already exists:

Output

C++ Overloading
C++ Cheat Sheet
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading