File Streams

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

We'll cover the following

File streams enable you to work with files. They need the header <fstream>. The file streams automatically manage the lifetime of their file.

Whether you use a file stream for input or 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 you to set the opening mode of a file stream. Here are a few of those flags:

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 on 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 1400+ tech skills courses.