File I/O

Differences
#include <fstream.h>
#include <stdlib.h>
Declare stream
Check on successful opening of file
Use stream name in I/O statements
Declaration
Format
streamtype streamname ("filename");
for streamtype ofstream or ifstream
streamname a programmer defined id
filename the name of the external file
Example
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>

main () {
  char ch;
  ofstream out ("sample.out");
  if (!out) {
    cerr << "File could not be opened" << endl;
    exit (1);
  }
  cout << "Please enter your section number\n";
  out << "Section: ";
  for (int i=0; i<4; i++) {
    cin >> ch;
    out << ch;
  }
  out << endl;
}
 

Back Home Up Next