Lecture Notes for Introduction to Computer Science II

17 July 2001 - More on File Streams


  1. stream errors

    1. file io may fail for many reasons - error reporting is complex; dealing with errors is complex

    2. eof is considered an error condition - there are others

    3. bool good(void) - true if no errors; false otherwise

      1. ifstream inf;
        const string fname = "my.dat";
        inf.open(fname.c_str());
        if (!inf.good())
          cerr << "Can't open " << fname << "\n";
        

      2. inf.read(data, data_size);
        if (inf.eof())
          // whatever
        if (!inf.good())
          // whatever
        

    4. bool operator!(stream) returns true if there are no errors

      1. operator! doesn't consider eof an error

      2. ifstream inf;
        const string fname = "my.dat";
        inf.open(fname.c_str());
        if (!inf)
          cerr << "Can't open " << fname << "\n";
        

    5. prefer good() over operator!

  2. opening files

    1. a second argument to open() describes how the file should be opened

      1. ios::in - open for reading, file pointer at the beginning of the file

      2. ios::out - open for writing, file pointer at the beginning of the file; this trashes the previous file contents

      3. ios::app - open for writing (appending), file pointer at the end of the file; this preserves the previous contents of the file

      4. the default for ifstreams is ios::in

      5. the default for ofstreams is ios::out - the default open for writes is destructive

      6. fstreams have no defaults - you must specify ios::in, ios::out, or ios::in + ios::out

    2. default fstream constructors can take the same arguments as open()

      1. ifstream inf("my.dat");

  3. reading and writing

    1. the void put(char) file stream member function

      1. write a character into the file at the file pointer

      2. advance the file pointer by one

    2. the int get(void) file stream member function

      1. read and return the character from the file at the file pointer

      2. advance the file pointer by one

      3. return -1 at eof

    3. the getline(ifstream, string) function

      1. defined in <string>, not in the stream includes

      2. it's not a member function - no dot access


This page last modified on 23 July 2001.