Slide 2.6: Reading and displaying file contents (cont.)
Slide 2.8: Seeking (cont.)
Home

Seeking


The preceding sample program reads a file sequentially, reading one byte after another until it reaches the end of the file. Sometimes we want to read or write without taking the time to go through every byte sequentially. An object of type fstream has two file pointers: The action of moving the get/put pointer directly to a certain position in a file is often called seeking. The following program performs the tasks:
  1. Reads the file test.txt, whose contents are

        <br>This is only a test.<br>

  2. Seeks the two <br> tags, whose offsets are 0 and 24, respectively.
  3. Replaces them by the tags <h1> and </h1>, respectively.
Seeking                              
#include <fstream>
#include <iostream>
#include <cstdlib>
  using namespace  std;

int  main( ) {
  long     pos;
  fstream  file;

  system    ( "cat test.txt" );
  file.open ( "test.txt", fstream::in | fstream::out );
  file.write( "", 4 );
  pos = file.tellp( );
  file.seekp( pos+ );
  file.write( "", 5 );;
  cout << "<br>The tags are changed.<br>";
  file.close( );
  system    ( "cat test.txt" );
}