C++ Files

basic file read write with stream operators

note the similarity between cin, cout and stream file io

// simply write a text file with all 2 digit odd numbers

#include <fstream>

void main()

{

    ofstream fout;

    fout.open("abc.txt");

    for (int i=11; i<100; i +=2)

        fout << i << endl; // one line has only one number

    fout.close();

}

// read the file back and print every number to console

#include <iostream>  // why do we need this now?

#include <fstream>

void main()

{

    ifstream fin;

    int i;

    while (!fin.eof()) {

        fin >> i;

        cout << i << endl;

     }

    fin.close();  // always a good idea to close it

}

// read the same file with string input

#include <iostream>

#include <fstream>

#include <string>

void main()

{

    ifstream fin;

    string s;

    while (! fin.eof()) {

        fin >> s;

        cout << s << " xxx " ;

    }

    fin.close();

}

Things to know

note also the difference between cin, cout and file io

note the difference between object and class

file open options (create, read, write, append, etc)

file error handling

using string and vector to process file content

Attachment (fileio.cpp) is a file IO exercise which extracts the 2nd word of every line from an input file to an output file.