Rogue Wave banner
Previous fileTop of DocumentContentsNext file

9.2 Working with File Streams

9.2.1 Creating and Opening File Stream Objects

There are two ways to create a file stream11: you can create an empty file stream, open a file, and connect it to the stream later on; or you can open the file and connect it to a stream at construction time. These two procedures are demonstrated in the two following examples, respectively:

or:

//1A file stream is created that is not connected to any file. Any operation on the file stream will fail.
//2Here a file is opened and connected to the file stream. If the file cannot be opened, ios_base::failbit will be set; otherwise, the file stream is now ready for use.
//3Here the file is both opened and connected to the stream.

9.2.2 Checking a File Stream's Status

Generally you can check whether the attempt to open a file was successful by examining the stream state afterwards; failbit will be set in case of failure.

There is also a function called is_open()that indicates whether a file stream is connected to an open file. This function does not mean that a previous call to open() was successful. To understand the subtle difference, consider the case of a file stream that is already connected to a file. Any subsequent call to open() will fail, but is_open() will still return true, as shown in the following code:

//1Open a file and connect the file stream to it.
//2Any subsequent open on this stream will fail.
//3Hence the failbit will be set.
//4However, is_open() still returns true, because the file stream still is connected to an open file.

9.2.3 Closing a File Stream

In the example above, it would be advisable to close the file stream before you try to connect it to another file. This is done implicitly by the file streams destructor in the following:

//1Here the file stream fil goes out of scope and the file it is connected to will be closed automatically.

You can explicitly close the connected file. The file stream is then empty, until it is reconnected to another file:

//1An empty file stream is created.
//2A file is opened and connected to the file stream.
//3Here we check whether the file was successfully opened. If the file could not be opened, the failbit would be set.
//4Now the file stream is usable, and the file's content can be read and processed.
//5Close the file again. The file stream is empty again.

Previous fileTop of DocumentContentsNext file

©Copyright 1998, Rogue Wave Software, Inc.
Send mail to report errors or comment on the documentation.


OEM Release, June 1998