File I/O
- fstream Library
- Streams: An abstract way of thinking about I/O
- A file "stream" is a sequence of symbols, e.g., This is a stream ....
that is about to end. <EOF>
- cin and cout are familiar streams for I/O
- Other "standard" streams are cerr (unbuffered) and clog
(buffered)
- Ordinarily cin is associated with the keyboard and cout,
cerr, and clog are associated with the monitor. This can
be changed with re-direction (see linux_II)
- File I/O: We can read and write files, using the common stream
operators "<<" and ">>" by using the fstream library
(keep in mind you "use" a library by including it and then
referencing it's objects)
- Some of the objects in fstream are: ifstreams (input
files) and ofstreams (output files) and fstreams (input-output files)
- Opening Files: stream files are opened either when they are
declared or with the member function open()
- e.g.: ifstream input_file("filename"); or
- e.g.: ofstream output_file; ...... output_file.open("filename");
- e.g.: fstream io_file; string "filename"; ......
io_file.open(filename.c_str());
- Reading/Writing to Files: stream files are read/written in the
exact same manner as cin ro cout using the stream operators "<<"
and ">>"
- e.g.: input_file >> variable;
- e.g.: output_file << variable;
- Closing Files: stream files are closed either when the program
terminates or with the member function close()
- e.g.: input_file.close();
- See file_io_example.cpp