io:examples

C++ Reference

C++ I/O Examples

Reading From Files

Assume that we have a file named data.txt that contains this text:

    Fry: One Jillion dollars.
    [Everyone gasps.]
    Auctioneer: Sir, that's not a number.
    [Everyone gasps.]

We could use this code to read data from the file, word by word:

    ifstream fin("data.txt");
    string s;
    while( fin >> s ) {
      cout << "Read from file: " << s << endl;
    }

When used in this manner, we'll get space-delimited bits of text from the file:

    Read from file: Fry:
    Read from file: One
    Read from file: Jillion
    Read from file: dollars.
    Read from file: [Everyone
    Read from file: gasps.]
    Read from file: Auctioneer:
    Read from file: Sir,
    Read from file: that's
    Read from file: not
    Read from file: a
    Read from file: number.
    Read from file: [Everyone
    Read from file: gasps.]

Note that in the previous example, all of the whitespace that separated words (including newlines) was lost. If we were interested in preserving whitespace, we could read the file in line-by-line using the I/O_getline()_function.

    ifstream fin("data.txt");
    const int LINE_LENGTH = 100;
    char str[LINE_LENGTH];
 
    while( fin.getline(str,LINE_LENGTH) ) {
      cout << "Read from file: " << str << endl;
    }

Reading line-by-line produces the following output:

    Read from file: Fry: One Jillion dollars.
    Read from file: [Everyone gasps.]
    Read from file: Auctioneer: Sir, that's not a number.
    Read from file: [Everyone gasps.]

If you want to avoid reading into character arrays, you can use the C++_string getline() function to read lines into strings:

    ifstream fin("data.txt");
    string s;
    while( getline(fin,s) ) {
      cout << "Read from file: " << s << endl;
    }

Checking For Errors

Simply evaluating an I/O object in a boolean context will return false if any errors have occurred:

    string filename = "data.txt";
    ifstream fin( filename.c_str() );
    if( !fin ) {
      cout << "Error opening " << filename << " for input" << endl;
      exit(-1);
    }