File Streams

Now, we shall learn how to communicate with files using C++.

File streams enable us to work with files. They need the header <fstream>. The file streams automatically manage their file for its whole lifetime.

Whether we use a file stream for input, output, or with the character type char or wchar_t there are various file stream classes:

Class Use
std::ifstream and std::wifstream File stream for the input of data of type char and wchar_t.
std::ofstream and std::wofstream File stream for the output of data of type char and wchar_t.
std::fstream and std::wfstream File stream for the input and output of data of type char and wchar_t.
std::filebuf and std::wfilebuf Data buffer of type char and wchar_t.

⚠️ Set the file position pointer
File streams used for reading and writing have to set the file position pointer after the contents change.

Flags enable us to set the opening mode of a file stream.

Flag Description
std::ios::in Opens the file stream for reading (default for std::ifstream and std::wifstream).
std::ios::out Opens the file stream for writing (default for std::ofstream and std::wofstream).
std::ios::app Appends the character to the end of the file stream.
std::ios::ate Sets the initial position of the file position pointer at the end of the file stream.
std::ios::trunc Deletes the original file.
std::ios::binary Suppresses the interpretation of an escape sequence in the file stream.

Flags for the opening of a file stream

It’s quite easy to copy the file named in to the file named out with the file buffer in.rdbuf(). The error handling is missing in this short example.

Get hands-on with 1200+ tech skills courses.