C++: Working with files -2

More about open(): File Modes

General form of open() function
The second argument mode specifies the purpose for which the file is opened.

The default value of mode are
   ios::in for ifstream function meaning open for reading only
   ios::out for ofstream function open for writing only

File Mode Parameters

ios::app   Appened to end-of-file
ios::ate    Go to end-of-file on opening
ios::binary   Binary file
ios::nocreate  Open fails if file doesn't exist
ios::noreplace  Open files if file already exist
ios::trunc  Delete the contents of file if it exists

File Pointers and their Manipulations

Each file has two associated pointers known as file pointer.
1. Input pointer(get pointer) is used for reading the contents of a given file location.
2. Output pointer(put pointer) is used for writing to a file location.

Functions for Manipulation of file Pointers

seekg() Moves get pointer to a specified location
seekp() Moves put pointer to a sp
ecified location
tellg()   Gives the current position of the get pointer
tellp()    Gives the current position of the put pointer

Specifying the offset

seek function seekg() and seekp() can also be used with two arguments as follows:

The parameter offset represents the no. of bytes the file pointer is to be moved from the location specified by the parameter refposition.

The refposition takes one of the following three constants defined in ios class
   ios::beg   start of file
   ios::cur    current position of pointer
   ios::end   end of file 
   fout.seekg(m.ios::beg);   Moves to (m+1) bytes in the file
   fout.seekg(-m.ios::end);   Go backward by m bytes from the end

Sequential Input and Output Operations

put() and get() are designed for handling a single character at a time.

write() and read() are designed to write and read blocks of binary data. This means that values are stored in the disk i the same format in which they are stored in the internal memory.

The binary input and output function takes the following form

  infile.read((char *)& V,sizeof(V));
  outfile.read((char *)& V,sizeof(V));

The first argument is the address of the variable V and the second is the length of the variable in bytes. The address of the variable must be cast to type char *(i.e. pointer to character type).

                   < Happy Coding >


In Association with Amazon.in