Positioning File Pointers


  • When you can open a file in more than one mode using the fstream class, it is not necessary to close the file and open it again when you need to switch from one mode to the other.
  • But if you are writing and reading in different positions of the file then, the stream pointers have to be positioned appropriately.
  • Each file object has associated with it two integer values called the get pointer and the put pointer.
  • These are also called the current get position and the current put position, or simply the current position.
  • These values specify the byte number in the file where reading or writing will take place.

    Functions To Move The File Pointer

  • seekg() and seekp()
  • seekg() - for get pointer
  • seekp() - for put pointer
  • These functions take two arguments.
  • The first argument is the relative offset i.e. the number of bytes the file pointer has to be moved. (+ for forward and - for backward.)
  • The second argument is the position of the file pointer from where the offset is to be considered. The default argument for this is the beg (beginning of the file). It can take values ios::beg (beginning), ios::end (end of file), and ios::cur (current pointer position).
  • .g.: seekg(-5, ios::end); moves the get pointer 5 bytes backward from the end of the file.

    THE tellg() or tellp() FUNCTION

  • These functions return the current position of the get or put pointer in bytes.
  • The following example illustrates the use of seekg() function. The seekp() function is also used in a similar manner whenever necessary.
    Click here for example

fstream<< Previous
Next >> Objects That Read And Write Themselves

Our aim is to provide information to the knowledge seekers.


comments powered by Disqus


Footer1