Intro to File Input/Output in C++


C++ File I/O

While redirection is very useful, it is really part of the operating system (not C++). In fact, C++ has a general mechanism for reading and writing files, which is more flexible than redirection alone.

Background knowledge:


I.  Streams
       A.  General concept
        B.  Istreams and Ostreams
        C.  Istream methods
        D.  Ostream methods

II. Sequential Files
        A.  general concept
        B.  Opening a file - ifstreams and ofstreams
        C.  Unformatted file input
        D.  Unformatted file output
       E.  Formatted file input
        F.  Formatted file output

III. Advanced stream methods

I. Streams

A.  General Concept

        In C++, I/O (input/output) occurs in streams of bytes.
A stream is simply a sequence of bytes.  Input streams receive bytes from
ome device (a file on a hard disk, the keyboard, or some other input
device),
while Output streams send a sequence of bytes to a device (the display,
a file on the hard disk, the printer, etc.).

        Any additional meaning or structure these bytes may have is
imposed by the program.  C++ provides both "low-level" and
"high-level" ways for manipulating streams.  Low level commands simply
specify the number of bytes to be received from or sent to the
stream.  High level I/O, also known as formatted I/O, allows
the programmer to to consider the bytes in the stream as grouped into
meaningful units reprsenting ints, floats, chars, strings, etc.

An input stream in C++ is called an istream.
An output stream in C++ is called an ostream.

You are already familiar with one input stream and one output stream:  cin
is
an input stream, while cout is an output stream.

---------------

II. Sequential Files

A sequential file is a collection of data stored on a disk. C++ views all
such files simply as a sequence of bytes.  Each file ends with a special
end of file marker. Sequential files have no additional inherent structure
- any additional structure must be imposed by the program reading and
writing the file.

A Class hierarchy:
                             ios
                            /   \
                      istream    ostream
                    /      \    /      \
                 ifstream    iostream    ofstream
                                |
                              fstream

[A] Opening a sequential file for reading/writing

To read a file in C++, one must declare a variable of type ifstream, and
associate it with the file.  An ifstream is a kind of istream.

Step 1: You must include the following header files at the top of your
program:
#include 
#include 

Step 2: Declare a variable of type ifstream/ofstream.  This variable is
sometimes called a file handle.

ifstream InFile;        // declares file handle called InFile
ofstream OutFile;       // declares file handle called OutFile
fstream InOutFile;

Step 3: Open the file for reading, using the ifstream member function
open().

InFile.open("datafilein.txt", ios::in);  //for reading only
OutFile.open("datafileout.txt", ios::out); //for writing
InOutFile.open("datafile",ios::in|ios::out); //for reading&writing

The first argument is the name of the file.  You can store the file name
in a variable and pass that variable as the argument.
The second argument(file open mode) indicates whether the file is to be
opened for reading or writing.

____________
other file open modes( see D&DP709 for details):
ios::app  write all output to the end of the file (append)
ios::ate  same as app, but can write anywhere
ios::trunc same as out
ios::nocreat  ios::noreplace (else fail)
______________

If a file was opened incorrectly, or if the open statement failed in any
way, then the ! operator applied to the file handle will have the value
false. Thus we can check if an open statement was successful with code
like:

char filename="datafile.txt";
InFile.open(filename, ios::in);
if (!InFile) {
        cout << "file "<< filename << " could not be opened."<< endl;
        exit(1);
        }

C] Unformatted file input

get (several versions):
 1. get with no arguments inputs one character
   while((c=cin.get())!=EOF) cout.put(c);
 2. get with a character argument stores in it the next character from the
input stream
   cin.get(c);
 3. get with three arguments: a character array, a size limit, and a
delimiter (default '\n').
    cin.get(buffer,size)
getline: like the third version of get
    cin.getline(buffer,size);
eof: cin.eof() is true when end-of-file is encountered.
read: inputs into a character array a designated number of characters
  cin.read(buffer,20);
( ******See D&D ch. 11.4.2/11.5 for details****)


[D] Unformatted file output
put: cout.put(c);
write: cout.write(buffer,size)

[EF] Formatted file input/output

The right shift operator(>>) is overloaded to designate stream input and
is
referred to as the stream-extraction operator, it's "smart enough" to
"know" what the type of data is, so no additional type information needs
to be specified.
Example:
     cin >> grade;
     cout << grade;
(stream-insertion operator( << ) is the similiar as >> . )


[G] Closing data files
  InFile.close();

------------------------------

III. Advanced stream methods

precision, setprecision
width, setw
stream format states and format state flags
justification
stream error states:  eofbit, failbit, badbit, rdstate, clear

( ******See D&D ch. 11.6/11.7 for details****)


BU CAS CS - Intro to File Input/Output in C++
This page created by Saratendu Sethi <sethi@cs.bu.edu>.
Modified by Elena Machkasova <elenam@cs.bu.edu> Material adapted for C++ from Intro to File Input/Output in C.