-
Notifications
You must be signed in to change notification settings - Fork 134
Input Output
The code examples you've seen so far in this tutorial have used the cout object, which automatically writes to the screen. However, one often wishes to write to files for longer-term storage. In addition, one often finds it necessary to read from existing files, e.g. to obtain data necessary for a computation.
There are two fundamental types of file-based input/output (I/O): formatted and unformatted. Formatted means that the data is written to/read from the file as integers, doubles, characters, etc., while unformatted means that the data is handled as raw bytes and (perhaps) interpreted later. Formatted files are convenient because they can be read by simple text editors like vi or emacs (or even Microsoft Word!), while unformatted files appear as gibberish to such programs. On the other hand, unformatted files are usually much more compact than formatted files, and they store numerical data with no additional loss of precision. In this section, we focus on formatted I/O as it's easier to learn and will get you started.
To use the functionality described here in a C++ program, you must use the standard I/O header file:
#include <iostream>
#include <fstream> // necessary for formatted I/O
However, it is also possible to make use of older (but often more convenient) C-language output:
#include <cstdio>
which provides declarations for functions like printf() that will be described below.
In C++-based I/O, writing to or reading from files involves special objects called "streams" of type "ifstream" (input stream) or "ofstream" (output stream). Three special C++ streams are:
First Header | Second Header |
---|---|
Content from cell 1 | Content from cell 2 |
Content in the first column | Content in the second column |