Input and output streams
David O. Yevick · Cambridge University Press eBooks · 2012
C++ implements a device-independent approach to reading and writing data such that nearly the same interface (the public class members) is employed to send data to or receive data from different devices such as disk files, memory buffers and the keyboard and terminal. This is achieved by collecting functions and variables common to all input and output operations into an ios base class. Operations involving the standard input device (keyboard) cin are appended in a derived istream class, while functionality that enables data to be read from files and memory buffers is incorporated in the ifstream and istrstream subclasses of istream , respectively. Output operations are implemented in the same manner by the corresponding output classes, ostream , ofstream and ostrstream . The iostream class multiply inherits the internal functions and variables of both the istream and ostream classes. Finally, the fstream and strstream classes further specialize the iostream class by appending the properties required to both read and write to files and memory buffers (alternatively e.g. fstream can multiply inherit from ofstream and ifstream) . Following the structure of the inheritance diagram, we first discuss the iostream class. Subsequently we discuss the interfaces to files and memory buffers associated with fstream and strstream . The iostream class and stream manipulators In C++, variables read into or written from a program initially reside in abstract objects termed streams, examples of which are cin and cout . These streams may be thought of as smart memory buffers enhanced through the inclusion of public, user-accessible functions that can act on the data stored in the stream buffer before its contents are processed by the program or sent to a device. The components that interface the memory buffer with the actual system devices are implemented as private functions and variables of the stream classes and are invisible to the user.