An Input/Output Stream Example

An object of type fstream is a single stream with two logical substreams, one for input and one for output. Although there are separately designated put and get positions in the underlying buffer, those positions are tied together.

If a file is not opened in append mode, changing the get position (with a seekg call) changes the put position (returned by a tellp call).

If a file is opened in append mode, write operations always occur at the end of the file. Each such write operation also changes the get position pointer to just past the last character in the file. A call to seekp also changes the get position.

Example 22

Example 22 reads the text file into a character array and writes an uppercase-only copy of the bytes at the end of the file:

// exios122.cpp

// An fstream file

#include <fstream.h>

#include <ctype.h>

void main()

{

fstream tfile( "test.dat", ios::in | ios::app );

char tdata[100];

int i = 0;

char ch;

while ( i < 100 ) {

tfile.get( ch );

if ( tfile.istream::eof() ) break;

tdata[i++] = ch;

}

tfile.istream::clear();

for ( int j = 0; j < i; j++ ) {

tfile.put( toupper( tdata[j] ) );

}

}

The program must call the clear member function before starting the write operations because the stream is at the end of the file. The clear function resets the end-of-file flag and all other flags, which allows the program to proceed with the output.