File IO Operations in C++

Feroz Ahmad bio photo By Feroz Ahmad Comment

Source : http://www.cplusplus.com/doc/tutorial/files/


I am just trying to keep the reading material organised for people and myself.


C++ provides the following classes to perform output and input of characters to/from files:

  • ofstream: Stream class to write on files
  • ifstream: Stream class to read from files
  • fstream: Stream class to both read and write from/to files.

For  writing into a file we declare an object of class ofstream and for reading a file object of class ifstream. Steps are as follows :

  1. Creating stream object.
  2. Opening the file
  3. Performing tasks (Reading/Writing)
  4. Closing the file

1. Creating Object

ofstream myfile; //to write
//or
ifstream myfile; //to read

2. Opening File

ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary); 
/*
open (filename, mode);
Where filename is a string representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags
*/

Combining step 1 and step 2,

ofstream myfile ("example.bin", ios::out | ios::app | ios::binary);
//Using the benefit of the contructor for the class ofstream
Member constant Opening mode
app (append) Set the stream's position indicator to the end of the stream before each output operation.
ate (at end) Set the stream's position indicator to the end of the stream on opening.
binary (binary) Consider stream as binary rather than text.
in (input) Allow input operations on the stream.
out (output) Allow output operations on the stream.
trunc (truncate) Any current content is discarded, assuming a length of zero on opening.

For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open member function (the flags are combined).

For fstream, the default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode (which is both input and output) is overridden, not combined.

To check if a file stream was successful opening a file, you can do it by calling to member is_open. This member function returns abool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:

if (myfile.is_open()) { /* ok, proceed with output */ }

3. Performing Operations

Text Files

// writing on a text file
#include 
#include 
using namespace std;

int main () {
  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}
// reading a text file
#include 
#include 
#include 
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

get and put stream objects:

ifstream, like istream, keeps an internal get position with the location of the element to be read in the next input operation.

ofstream, like ostream, keeps an internal put position with the location where the next element has to be written.

Finally, fstream, keeps both, the get and the put position, like iostream.

These internal stream positions point to the locations within the stream where the next reading or writing operation is performed.

tellg() and tellp()

no parameters return a value of the member type streampos,  the current get position (in the case of tellg) or the put position (in the case of tellp).

seekg() and seekp()

allow to change the location of the get and put positions. Both functions are overloaded with two different prototypes. The first form is:

seekg ( position ); seekp ( position ); Using this prototype, the stream pointer is changed to the absolute position position (counting from the beginning of the file). The type for this parameter is streampos, which is the same type as returned by functions tellg and tellp.

The other form for these functions is:

seekg ( offset, direction ); seekp ( offset, direction ); Using this prototype, the get or put position is set to an offset value relative to some specific point determined by the parameter direction. offset is of type streamoff. And direction is of type seekdir, which is an enumerated type that determines the point from where offset is counted from, and that can take any of the following values:

ios::beg offset counted from the beginning of the stream
ios::cur offset counted from the current position
ios::end offset counted from the end of the stream

 


 

Binary Files

For binary files, reading and writing data with the extraction and insertion operators (<< and >>) and functions like getline is not efficient, since we do not need to format any data and data is likely not formatted in lines.

File streams include two member functions specifically designed to read and write binary data sequentially: write and read. The first one (write) is a member function of ostream (inherited by ofstream). And read is a member function of istream (inherited byifstream). Objects of class fstream have both. Their prototypes are:

write ( memory_block, size ); read ( memory_block, size );

 

// obtaining file size
#include 
#include 
using namespace std;

int main () {
  streampos begin,end;
  ifstream myfile ("example.bin", ios::binary);
  begin = myfile.tellg();
  myfile.seekg (0, ios::end);
  end = myfile.tellg();
  myfile.close();
  cout << "size is: " << (end-begin) << " bytes.\n";
  return 0;
}
// reading an entire binary file
#include 
#include 
using namespace std;

int main () {
  streampos size;
  char * memblock;

  ifstream file ("example.bin", ios::in|ios::binary|ios::ate);
  if (file.is_open())
  {
    size = file.tellg();
    memblock = new char [size];//we request the allocation of a memory block large enough to hold the entire file
    file.seekg (0, ios::beg);
    file.read (memblock, size);
    file.close();

    cout << "the entire file content is in memory";

    delete[] memblock;
  }
  else cout << "Unable to open file";
  return 0;
}

4. Closing a file

Once this member function is called, the stream object can be re-used to open another file, and the file is available again to be opened by other processes.

myfile.close();

In case that an object is destroyed while still associated with an open file, the destructor automatically calls the member function close.


Concept of Buffer and Syncronization

When we operate with file streams, these are associated to an internal buffer object of type streambuf. This buffer object may represent a memory block that acts as an intermediary between the stream and the physical file. For example, with an ofstream, each time the member function put (which writes a single character) is called, the character may be inserted in this intermediate buffer instead of being written directly to the physical file with which the stream is associated.The operating system may also define other layers of buffering for reading and writing to files.

When the buffer is flushed, all the data contained in it is written to the physical medium (if it is an output stream). This process is called synchronization and takes place under any of the following circumstances:

  • When the file is closed: before closing a file, all buffers that have not yet been flushed are synchronized and all pending data is written or read to the physical medium.
  • When the buffer is full: Buffers have a certain size. When the buffer is full it is automatically synchronized.
  • Explicitly, with manipulators: When certain manipulators are used on streams, an explicit synchronization takes place. These manipulators are: flush and endl.
  • Explicitly, with member function sync(): Calling the stream's member function sync() causes an immediate synchronization. This function returns an int value equal to -1 if the stream has no associated buffer or in case of failure. Otherwise (if the stream buffer was successfully synchronized) it returns 0.
comments powered by Disqus