COMP 151 : Lab 04

Objective:

file input and output

Download:

  count.cpp

  571 (text file)

Reference:

   text book section 20

   cplusplus.com

Lab Work:

   Input / Output Stream
    Input Stream

   Output Stream

   File I/O
   Open Files

   Close Files

   Text Files Input / Output

   State Flags

   File Position

Input / Output Stream

Besides << and >>, there are additional input/output operator which allow us to read/write the stream as a sequence of bytes rather than as a sequence of data types, such as char, int, string, and so on.

Input Stream

get(char) - reads the input stream one byte at a time, including white spaces. For example:

char ch;
while ( cin.get(ch) ) {
    //... ...
}


int get() - also reads a character from the input stream, except that it returns the value of type int rather than the istream object.

int ch;
while ( (ch = cin.get()) != EOF ) {
    //... ...
}

EOF is a constant representing the end-of-file.


get(char *line, streamsize size, char delimiter='\n') - reads a number of characters from the input stream.

char line[1024];
while ( cin.get(line, 1024) ) {
    //... ...
}

Notice that the delimiter is not read and is left as the next character on the stream.


getline(char *line, streamsize size, char delimiter='\n') - also reads a number of characters from the input stream.

char line[1024];
while ( cin.getline(line, 1024) ) {
    //... ...
}

The difference is that getline() discards the delimiter from the stream, while get(line, 1024) does not.


Some other functions:

read( char*line, streamsize size) - extracts size contiguous bytes from the input stream

peek() - returns the next character but does not extract it from the istream

unget() - resets the reading pointer backward by one

putback(char) - pushes the character back onto the stream

gcount() - returns the number of characters got in the last operation

ignore( streamsize length = 1, int delimiter = traits::eof)

Top

Output Stream

put(char) - outputs a character to the output stream

char ch;
while ( cin.get(ch) ) {
    cout.put(ch);        // echo everything
}


write( const char *line, streamsize size) - outputs size characters from the line character array

char line[1024];
while ( cin.getline(line, 1024) ) {
    write ( line, cin.gcount() );        // echo lines
}

Top

File I/O

   C++ provides support for input and output with files through the following classes:

ofstream: File class for writing operations (derived from ostream)

ifstream: File class for reading operations (derived from istream)

fstream: File class for both reading and writing operations (derived from iostream)

Open File

The open file is represented within the program by the stream (the object of one of these classes) and any input or output performed on it will apply to the physical file.

In order to open a file use the member function open();

void open (const char * filename, openmode mode);

   filename is a string of characters representing the name of the file to be opened

   mode is a combination of the following flags:

ios::in Open file for reading
ios::out Open file for writing
ios::ate Incial position: end of file
ios::app Every output is appended at the end of file
ios::trunc If the file already existed it is erased
ios::binary Binary mode

These flags can be combined using bitwise operator OR: |. For example, if we want to open the file "test.bin" in binary mode to add data we could do it by the following call to function-member open:

ofstream file;
file.open ("test.bin", ios::out | ios::app | ios::binary);

The member functions open of classes ofstream, ifstream and fstream all include a default mode (that varies from one to the other):

class default mode to parameter
ofstream ios::out | ios::trunc
ifstream ios::in
fstream ios::in | ios::out

The default value is only applied if the function is called without the mode parameter. If the function is called with any value in that parameter the default mode is not used.

Since frequently the first task that is performed on an object of classes ofstream, ifstream and fstream is to open a file, we could combine the two previous lines in the object declaration as follows:

ofstream file ("test.bin", ios::out | ios::app | ios::binary);

Both forms of opening a file are valid.


You can check if a file has been correctly opened by calling the member function is_open():

bool is_open();

For example;

if (file.is_open()) {
    cerr << "error: unable to open input file\n";
       return -1;
}

returns a bool type value indicating true if the object is correctly associated with an open file or false if it is not.

You can also check the file handle:

if ( !file) {
    cerr << "error: unable to open input file\n";
    return -1;
}

Top

Close File

When reading, writing or consulting operations on a file have been completed we must close it so that it become again available. Closing will also flush the memory buffer to the file. We can close a file by calling the member function close().

void close ();

For example:

file.close();

Once this member function is called, the object can be used to open another file.

In the case that an object is destructed and is still associated to an open file, the destructor will automatically call the member function close

Top

Text Files Input / Output

Reading and writing of text files uses the same members as those used for communicating with the console. As an example, in the following we use the (overloaded) insertion operator <<:

// writing on a text file
#include <fstream.h>

int main () {
  ofstream fout ("out.txt");
  if (fout.is_open())
  {
    fout << "Comp151 lab5.\n";
    fout << "File input / output.\n";
    fout.close();
  }
  return 0;
}
file out.txt

Comp151 lab5.
File input / output.

Data input from file can be similarly performed using cin:

// reading a text file
#include <iostream.h>
#include <fstream.h>

int main () {
  char buffer[256];
  ifstream fin ("out.txt");
  if (! fin.is_open())
  { cout << "Error opening file"; exit (1); }

  while (! fin.eof() )
  {
    fin.getline (buffer,100);
    cout << buffer << endl;
  }
  return 0;
}
terminal

Comp151 lab5.
File input / output.

This last example reads a text file and prints out its content on the screen. Notice that we have used a new member function, called eof that ifstream inherits from class ios and that returns true when the end of the file has been reached.

Top

State Flags

esides eof() there exist other member functions to verify the state of the stream (all of them return a bool value):
bad() Returns true if any failure occurs in a reading or writing operation. For example if there was an attempt to try to write to a file that is not open for writing (the same with reading) or if the device where it attempted to write has no space left.
fail()
Returns true in the same cases than bad() as well as in cases of format errors, e.g., if it tried to read an integer number and an alphabetical character is received.
eof()
Returns true if a file opened for reading has arrived at its end.
good()
This is the most generic: returns false if calling any of the previous flags would return true.
In order to reset the state of the flags checked by the previous member functions you can use the member function clear(), without specifying any parameter.

Top

File Position

tellg() and tellp()
returns the current position of get stream pointer (in case of tellg) or put stream pointer (in case of tellp).

seekg() and seekp()
This pair of functions changes the position of stream pointers get and put. Both functions are overloaded with two different prototypes:

seekg ( pos_type position );
seekp ( pos_type position );

This prototype changes the stream pointer to an absolute position from the beginning of the file. The type required is of the same one as returned by functions tellg and tellp.


seekg ( off_type offset, seekdir direction );
seekp ( off_type offset, seekdir direction );
Using this prototype, one can specify an offset from a concrete point determined by parameter direction, that can be:
ios::beg offset specified from the beginning of the stream
ios::cur offset specified from the current position of the stream pointer
ios::end offset specified from the end of the stream

Top

Assessment Task:

There is no assessment task in this lab