File streams allow input and output to files. Unlike the C stdio functions for file I/O, however, file streams follow the idiom which Stroustrup puts forth on page 366 of The C++ Programming Language, 3rd Edition: "Resource acquisition is initialization." In other words, file streams provide an advantage in that you can open a file on construction of a stream, and the file is closed automatically on destruction of the stream. Consider the following code:
void use_file(const char* fileName) { FILE* f = fopen("fileName", "w"); // use file fclose(f); }
If an exception is thrown while the file is in use here, the file is never closed. With a file stream, however, the file is closed whenever the file stream goes out of scope, as in the following example:
void use_file(const char* fileName) { std::ofstream f("fileName"); // use file }
Here the file is closed even if an exception occurs during use of the open file.
There are three class templates that implement file streams: basic_ifstream, basic_ofstream, and basic_fstream. These templates are derived from the stream base class template basic_ios. Therefore, they inherit all the functions for formatted input and output described in Chapter 28, as well as the stream state. They also have functions for opening and closing files, and a constructor that allows opening a file and connecting it to the stream. For convenience, there are the typedefs std::ifstream, std::ofstream, and std::fstream, with std::wifstream, std::wofstream, and std::wfstream for the respective narrow and wide character file streams.
The buffering is implemented by a specialized stream buffer class template, basic_filebuf.
In a large character set environment, a file is assumed to contain multibyte characters. To provide the contents of a such a file as a wide character sequence for internal processing, wifstream and wofstream perform corresponding conversions. The actual conversion is delegated to the file buffer, which relays the task to the imbued locale's code conversion facet.