Rogue Wave banner
Previous fileTop of DocumentContentsIndexNext file

9.1 About File Streams

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:

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:

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>.

9.1.1 The Difference between Predefined Streams and File Streams

The main differences between a predefined standard stream and a file stream are:

9.1.2 Code Conversion in Wide Character Streams

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.


Previous fileTop of DocumentContentsIndexNext file

OEM Edition, ©Copyright 1999, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.