UNIT VI Streams & Files in C++: Stream classes, stream errors, disk file I/O with streams, File...

Preview:

DESCRIPTION

Stream Class Hierarchy

Citation preview

UNIT VI

Streams & Files in C++: Stream classes, stream errors, disk file I/O with streams, File pointers, Error handling in file I/O. File I/O with members functions, overloading the extractions & insertion operators, Memory as a stream object, command-line arguments, Persistent Objects

Stream Classes A stream is a general name given to a flow of data. In C++ a stream is represented by an object of a particular class. Example - cin and cout are stream objects. Different streams are used to represent different kinds of data flow. For example, the ifstream class represents data flow from input disk files.

Advantages of Streams• Simple to Use. There are no formatting characters (such as %d ) in streams,

since each object already knows how to display itself. This removes a major source of errors.

• Existing operators and functions can be overloaded. For Ex - the insertion (<<) and extraction (>>) operators. This makes your own classes work in the same way as the built-in types, which again makes programming easier and more error free.

Stream Class Hierarchy

The ios Class• The ios class is the granddaddy of all the stream classes,

and contains the majority of the features to operate C++ streams.

• The three most important features are –1. Formatting flags 2. Error-status flags3. File operation mode.

1. Formatting Flags• Formatting flags are a set of enum definitions in ios.

They act as on/off switches that specify choices for various aspects of input and output format and operation.

ManipulatorsManipulators are formatting instructions inserted directly into a stream.

Examples – 1. Endl manipulator

sends a newline to the stream. cout << “To each his own.” << endl;

2. setiosflags() manipulator cout << setiosflags(ios::fixed) // use fixed decimal point

<< setiosflags(ios::showpoint) // always show decimal point<< var;

FunctionsThe ios class contains a number of functions that you can use to set the formatting flags and perform other tasks.

Examples - cout.width(14);cout.fill(‘*’);cout.setf(ios::left);cout.unsetf(ios::left);

The istream Class

The istream class, which is derived from ios, performs input-specific activities, or extraction.

The ostream ClassThe ostream class handles output or insertion activities.

Stream ErrorsError-Status BitsThe stream error-status flags constitute an ios enum member that reports errors that occurred in an input or output operation.

Recommended