CS102 Lecture Notes -- Simple File I/O in C++

James S. Plank

April 3, 2007.

For a nice treatment of file I/O, read the instructional material in http://www.cs.hmc.edu/~geoff/classes/hmc.cs070.200109/notes/io.html.

To illustrate, take a look at wordprint.cpp:

#include <iostream>
#include <fstream>
using namespace std;

main(int argc, char **argv)
{
  ifstream in_fp;
  ofstream out_fp;
  string s;

  if (argc != 3) {
    cout << "Usage: wordprint inputfile outputfile\n";
    exit(1);
  }
  in_fp.open(argv[1]);
  if (in_fp.fail()) {
    cout << "Couldn't open " << argv[1] << endl;
    exit(1);
  }
  out_fp.open(argv[2]);
  if (out_fp.fail()) {
    cout << "Couldn't open " << argv[2] << endl;
    exit(1);
  }
  while (!in_fp.fail()) {
    in_fp >> s;
    if (!in_fp.fail()) out_fp << s << endl;
  }
}

Note, it opens the file specfied by the first command line for reading, and it opens the file specified by the second command line for writing. It then reads in every word from the first file, and writes it on its own line in the second file. Note the use of the fail() method to test for successfull opening, and for testing for the end-of-file. Here it is working. Note how on my last call, I use a file in another directory:

UNIX> g++ -o wordprint wordprint.cpp
UNIX> wordprint
Usage: wordprint inputfile outputfile
UNIX> cat input.txt
This latest exponent of heresy is goaded into an attack.
UNIX> wordprint input.txt output.txt
UNIX> cat output.txt
This
latest
exponent
of
heresy
is
goaded
into
an
attack.
UNIX> cat /home/plank/cs102/Examples/5A/5a-4.txt
25 a b c d e f g $ ~
UNIX> wordprint /home/plank/cs102/Examples/5A/5a-4.txt output.txt
UNIX> cat output.txt
25
a
b
c
d
e
f
g
$
~
UNIX>