IO File Streams


I/O File Streams

I/O file streams require the inclusion the header: fstream. In addition the program also needs the I/O classes required to do file I/O including:

image from book

 ifstream // for input of files only ofstream // for output of files only fstream // for both input and output 

image from book

Each of these classes has two constructors that help to maintain the I/O streams. The constructors include one with a void signature and one with a signature that has three arguments which are:

  • a string (which is the name of the file)

  • a mode (which determines the type of I/O and may be a default argument)

  • an int (which is used to control network I/O)

These constructors are:

image from book

 ifstream(); ifstream(char* filename, ios::openmode mode = ios::in, int protect = filebuf::openprot); ofstream(); ofstream(char* filename, ios::openmode mode = ios::out, int protect = filebuf::openprot); fstream(); fstream(char* filename, ios::openmode mode, int protect = filebuf::openprot); 

image from book

 Note:  The use of the default arguments in two of the constructors above and how these constructors are used are discussed below. The use of ios and filebuf indicate that an enumerator (e.g. ios::out) of the enumerated data types ios and filebuf are being used.

 Warning:  Some compilers do not support the defaults listed above. You should check your compiler's manuals to determine whether these defaults are supported.

 Note:  The argument protect listed in the constructors above will not be discussed in these notes beyond this point. The discussion of the purpose of this argument is a topic for an advanced C++ course. It is only mentioned here to make you aware that these constructors have this argument. This is an argument that is needed in networked environments.

It is possible to create text I/O streams using these constructors as in the following examples:

image from book

 ifstream theFile("test.txt"); ostream theFile("test.txt"); fstream theFile("test.txt", mode); // the value options of                                         // the variable mode will                                         // be discussed later 

image from book

 Note:  In the examples about the object: theFile was used and the text file: text.txt was used. There is nothing specific about these names and any name could be used.

For examples of text files that use these concepts see: textin.cpp and textout.cpp

For another example check the following two programs: datain.cpp and dataout.cpp. Notice in these two examples that int and float variables are being used for input and output rather than input and output using a character at a time as in the previous two examples.




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net