Streams and file I/O

Streams and file I/O

Reading from a file and writing to another file

Read three integers from the file “input.dat”, and write them squared into the file “output.dat”

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

int main () {

  int x, y, z;

  // input stream
  ifstream fin;
  fin.open("input.dat");
  
  fin >> x;
  fin >> y;
  fin >> z;
 
  fin.close();

  // output stream
  ofstream fout;
  fout.open("output.dat");

  fout << x*x << endl;
  fout << y*y << endl;
  fout << z*z << endl;

  fout.close();
}

Reading the entire file using a while loop

The loop condition fails when you reach the end of file, when nothing could be read.

#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

int main () {
  
  // input stream
  ifstream fin;
  fin.open("input.dat");
  
  // check that the file was opened successfully
  // otherwise exit
  if (fin.fail()) {
    cout << "File not found!" << endl;
    exit(1);
  }

  int x;
  int i = 0;

  while( fin >> x ) {
    cout << x << endl;
    i++;
  }

  cout << "i = " << i << endl;

  fin.close();

}

Reading all characters one by one, without skipping whitespace

We can use the ifstream member function get.

The following program prints out the contents of the file “p4.cpp” on the screen, preserving all the original whitespace characters:

#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

int main () {
  
  // input stream
  ifstream fin;
  fin.open("p4.cpp");
  
  // check that the file was opened successfully
  // otherwise exit
  if (fin.fail()) {
    cout << "File not found!" << endl;
    exit(1);
  }

  char c;

  while( fin.get(c) ) {
    cout << c;
  }

  fin.close();

}

Formatting

Please refer to the book for more information on stream output formatting.

#include <iostream>
#include <cstdlib>
#include <fstream>

#include <iomanip>

using namespace std;

const int N = 3;

void print_table() {

  double data[N][N] = {
    { 1.0, 2.22, 0.000003333 },
    { 11.0, 2.222222, 0.000000003333 },
    { 111.0, 2.22222222222, 0.00000000003333 },
  };

  cout << endl;

  for (int i = 0; i<N; i++) {
    for (int j = 0; j<N; j++) {
      cout.width(10);
      cout << data[i][j] << ' ';
    }
    cout << endl;
  }

  cout << endl;
}


int main () {

  cout.setf(ios::scientific);
  print_table();

  cout.unsetf(ios::scientific);
  print_table();

}

1.000000e+00 2.220000e+00 3.333000e-06 
1.100000e+01 2.222222e+00 3.333000e-09 
1.110000e+02 2.222222e+00 3.333000e-11 


         1       2.22  3.333e-06 
        11    2.22222  3.333e-09 
       111    2.22222  3.333e-11