Lecture Notes for Introduction to Computer Science II
12 July 2001 - File Streams
- a file is represented as a file stream inside a c++ program.
- three file stream classes
-
ifstream
- file streams that read files
-
ofstream
- file streams that write files
-
fstream
- file streams that read and write files
- defined in the
<fstream>
include file
- opening and closing files
- the stream member function
open()
connects a file stream to a
file
-
void open(const char fname[])
- the file must exist
- the stream member function
close()
breaks the connection between a
file stream and a file
-
void close(void)
- file-stream instances going out of scope are closed automatically
- close them explicitly anyway
- reading and writing files
- another part of a file - the file pointer
- think of it as the current index
- reads and writes start at the file pointer
- reads and writes move the file pointer
- the stream member function
void read(char data[], int data_size)
- read at most
data_size
bytes from the file stream into data
- reading begins at the file pointer
- file pointer moves to the next byte after the last byte read
- file data are unchanged
-
ifstream
and fstreams
only
- the stream member function
void write(const char data[], int data_size)
- write
data_size
bytes from data
into the file stream
- writing begins at the file pointer
- file pointer moves to the next byte after the last byte written
- file data are changed
-
ofstream
and fstreams
only
- sequential file i-o - march through the file byte-by-byte from start to
finish without skipping bytes
- the end-of-file (eof) condition
- what happens when the last byte is read
- the file pointer is one past the end of the file - the eof condition
- reading at eof does nothing - returns no data, leaves the file pointer
unchanged
- the
bool eof(void)
stream member function returns true at eof,
false otherwise
- you can't discover eof until you try to read - you can't tell if
anybody's home until you knock on the door
-
while (!inf.eof())
inf.read(data, data_size);
is wrong
-
while (true) {
inf.read(data, data_size);
if (inf.eof()) break;
}
is right
- reading five bytes from a four byte file
- partial reads - reading fewer bytes than specified
- partial reads set the eof condition - trying to read the byte that
doesn't exist
- the stream member function
int gcount(void)
returns the number
of bytes last read
- be careful - partial reads don't necessarily indicate an eof
condition
- none of this applies to writing files
This page last modified on 23 July 2001.