Previous fileTop of DocumentContentsIndex pageNext file
Apache C++ Standard Library User's Guide

30.2 Working with File Streams

30.2.1 Creating and Opening File Stream Objects

There are two ways to create a file stream: 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:


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

NOTE -- The traditional iostreams supported a constructor, taking a file descriptor, that allowed connection of a file stream to an already open file. This is not available in the standard iostreams. However, this implementation of the standard iostreams provides a corresponding extension. See Appendix B of the Apache C++ Standard Library Reference Guide for more information.

30.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 is set in case of failure.

There is also a member 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() fails, but is_open() still returns true, as shown in the following code:

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

30.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 code:

//1Here the file stream file goes out of scope and the file it is connected to is 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 DocumentContentsIndex pageNext file