22C:030/115 Computer Science III

Fall 2001

A simple example program illustrating file I/O

(Authored by Nate Brixius.)
#include <fstream.h>

void writeFile(char *filename)
{
  ofstream f;

  f.open(filename);
  
  f << "Sammy Sosa 123 456" << endl;
  f << "Barry Bonds 789 456" << endl;
  
  f.close();
}

void readFile(char *filename)
{
  ifstream f;

  char first[20];
  char last[20];
  int val1, val2;

  f.open(filename);
  
  while(f && (f.peek() != EOF))
    {
      f >> first;
      f >> last;
      f >> val1;
      f >> val2;
      if(f.peek() == '\n')
        f.ignore(); // skip over the newline character
      
      cout << first << "," << last << "," << val1 << "," << val2 << endl;
    }

  f.close();
}


int main()
{
  writeFile("my.dat");
  readFile("my.dat");
}