File streams allow input and output to files. Unlike the C stdio functions for file I/O, however, file streams follow Stroustrup's idiom: "Resource acquisition is initialization."8 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) { 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 <charT,traits>, basic_ofstream <charT,traits>, and basic_fstream <charT,traits>. These templates are derived from the stream base class basic_ios <charT, traits>. Therefore, they inherit all the functions for formatted input and output described in Chapter 7, 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 regular typedefs ifstream, ofstream, and fstream, with wifstream, wofstream, and wfstream for the respective tiny and wide character file streams.
The buffering is done through a specialized stream buffer class, basic_filebuf <charT,traits>.
The main differences between a predefined standard stream and a file stream are:
A file stream needs to be connected to a file before it can be used. The predefined streams can be used right away, even in static constructors that are executed before the main() function is called.
You can reposition a file stream to arbitrary file positions. This usually does not make any sense with the predefined streams, as they are connected to the terminal by default.
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.
OEM Edition, ©Copyright 1999, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.