uses both seekp( ) and seekg( ) to reverse the first characters in a file. : file pointer « File Stream « C++ Tutorial






#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
   
int main(int argc, char *argv[])
{
  if(argc!=3) {
    cout << "Usage: Reverse <filename> <num>\n";
    return 1;
  }
   
  fstream inout(argv[1], ios::in | ios::out | ios::binary);
   
  if(!inout) {
    cout << "Cannot open input file.\n";
    return 1;
  }
   
  long e, i, j;
  char c1, c2;
  e = atol(argv[2]);
   
  for(i=0, j=e; i<j; i++, j--) {
    inout.seekg(i, ios::beg);
    inout.get(c1);
    inout.seekg(j, ios::beg);
    inout.get(c2);
   
    inout.seekp(i, ios::beg);
    inout.put(c2);
    inout.seekp(j, ios::beg);
    inout.put(c1);
  }
   
  inout.close();
  return 0;
}








12.6.file pointer
12.6.1.change file at given position
12.6.2.get file content at given position
12.6.3.Change a file at specific position
12.6.4.Check ofstream current marker position
12.6.5.move to position 2 in the stream and output a 0 in position 2
12.6.6.Tell the current position
12.6.7.seek and Skip
12.6.8.Test File Position
12.6.9.Seek 0 to reset the file pointer
12.6.10.seekg( ) moves the pointer offset number of characters from the specified origin
12.6.11.uses both seekp( ) and seekg( ) to reverse the first characters in a file.
12.6.12.Detecting EOF