Search⌘ K

File Streams

Explore how to handle file operations in C++ using streams such as ifstream, ofstream, and fstream. Understand file opening modes, position pointer management, and random access methods to read and write files safely and efficiently.

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:

...