File input and output (I/O) aren't glamorous parts of computer programming, but they are fundamental and therefor important. Contemporary C++ programs replace many file I/O operations with database or GUI operations. Nevertheless, these high-level operations rest on C++'s lower-level I/O operations and on an OS's low-level operations. Without file I/O operations, programs can only process small amounts of data and can only produce limited amounts of usable output. The large number of C++ API functions coupled with the many bewildering options exasperates the situation, making it essential that we learn how to use language-specific documentation.
When a program transfers data to or from a file, either reading or writing it, we can view the data as a stream or sequence of bytes. Hence, the C++ objects that perform I/O operations are called stream objects or simply streams. We'll organize the C++ I/O features in four ways to help manage their complexity:
Stream names. The stream class names typically include one or more characters that signal their use or behavior. For example, the "c" in cin and cout indicate that read from and write to the console. Additionally, "i" and "o," signify input and output, while "f" (for file) signifies both.
File type. Roughly speaking, files contain either textual or binary data. Both kinds of files can be further divided into more specialized types of data, and the following sections explore some of these. Opening a file as the correct type is essential for C++ programs running on the Windows operating system.
Transfer units. C++ program can transfer data, read or write it, as single characters, lines, or blocks, depending on the problem the program solves.
Transfer order. C++ programs typically access file data sequentially (from the beginning to the end in order) or randomly. Here, "random" means that the order isn't predetermined - the order of I/O is determined by outside factors. Direct access is a specialized form of random access used to implement many database operations.
Know
How to represent files as stream objects
What the file position pointer is and does
How to open a file (stream) in text and binary mode
How to close a file (stream)
How to use the file status functions: good, bad, and fail
How to read/write a file
One character at a time
One line at a time
Know about less common features
The difference between sequential and random access
How to read/write a file one block at a time
Buffer I/O
the gcount function
Random access file pointer positioning functions: seekg, seekp, tellg, and tellp