Lecture Notes for Introduction to Computer Science II

12 July 2001 - File Streams


  1. a file is represented as a file stream inside a c++ program.

  2. three file stream classes

    1. ifstream - file streams that read files

    2. ofstream - file streams that write files

    3. fstream - file streams that read and write files

    4. defined in the <fstream> include file

  3. opening and closing files

    1. the stream member function open() connects a file stream to a file

    2. void open(const char fname[])

    3. the file must exist

    4. the stream member function close() breaks the connection between a file stream and a file

    5. void close(void)

    6. file-stream instances going out of scope are closed automatically

      1. close them explicitly anyway

  4. reading and writing files

    1. another part of a file - the file pointer

      1. think of it as the current index

      2. reads and writes start at the file pointer

      3. reads and writes move the file pointer

    2. the stream member function void read(char data[], int data_size)

      1. read at most data_size bytes from the file stream into data

      2. reading begins at the file pointer

      3. file pointer moves to the next byte after the last byte read

      4. file data are unchanged

      5. ifstream and fstreams only

    3. the stream member function void write(const char data[], int data_size)

      1. write data_size bytes from data into the file stream

      2. writing begins at the file pointer

      3. file pointer moves to the next byte after the last byte written

      4. file data are changed

      5. ofstream and fstreams only

    4. sequential file i-o - march through the file byte-by-byte from start to finish without skipping bytes

  5. the end-of-file (eof) condition

    1. what happens when the last byte is read

    2. the file pointer is one past the end of the file - the eof condition

    3. reading at eof does nothing - returns no data, leaves the file pointer unchanged

    4. the bool eof(void) stream member function returns true at eof, false otherwise

    5. you can't discover eof until you try to read - you can't tell if anybody's home until you knock on the door

      1. while (!inf.eof())
          inf.read(data, data_size);
        
        is wrong

      2. while (true) {
          inf.read(data, data_size);
          if (inf.eof()) break;
          }
        
        is right

      3. reading five bytes from a four byte file

        1. partial reads - reading fewer bytes than specified

        2. partial reads set the eof condition - trying to read the byte that doesn't exist

        3. the stream member function int gcount(void) returns the number of bytes last read

        4. be careful - partial reads don't necessarily indicate an eof condition

      4. none of this applies to writing files


This page last modified on 23 July 2001.