Chapter 8. The IO Library
CONTENTS Section 8.1 An Object-Oriented Library284Section 8.2 Condition States287Section 8.3 Managing the Output Buffer290Section 8.4 File Input and Output293Section 8.5 String Streams299Chapter Summary302Defined Terms302In C++, input/output is provided through the library. The library defines a family of types that support IO to and from devices such as files and console windows. Additional types allow strings to act like files, which gives us a way to convert data to and from character forms without also doing IO. Each of these IO types defines how to read and write values of the built-in data types. In addition, class designers generally use the library IO facilities to read and write objects of the classes that they define. Class types are usually read and written using the same operators and conventions that the IO library defines for the built-in types.This chapter introduces the fundamentals of the IO library. Later chapters will cover additional capabilities: Chapter 14 will look at how we can write our own input and output operators; Appendix A will cover ways to control formatting and random access to files.Our programs have already used many IO library facilities:istream (input stream) type, which supports input operationsostream (output stream) type, which provides output operationscin (pronounced see-in) an istream object that reads the standard input.cout (pronounced see-out) an ostream object that writes to the standard outputcerr (pronounced see-err) an ostream object that writes to the standard error. cerr is usually used for program error messages.operator >>, which is used to read input from an istream objectoperator <<, which is used to write output to an ostream objectgetline function, which takes a reference to an istream and a reference to a string and reads a word from the istream into the string
This chapter looks briefly at some additional IO operations, and discusses support for reading and writing files and strings. Appendix A covers how to control formatting of IO operations, support for random access to files, and support for unformatted IO. This primer does not describe the entire iostream libraryin particular, we do not cover the system-specific implementation details, nor do we discuss the mechanisms by which the library manages input and output buffers or how we might write our own buffer classes. These topics are beyond the scope of this book. Instead, we'll focus on those portions of the IO library that are most useful in ordinary programs.