Reverses the first N characters within a file : fstream « File « C++






Reverses the first N characters within a file

  
#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[])
{
  long n, i, j;
  char ch1, ch2;

  if(argc!=3) {
    cout << "Usage: Reverse <filename> <num>\n";
    return 1;
  }

  fstream finout(argv[1], ios::in | ios::out | ios::binary);

  if(!finout) {
    cout << "Cannot open input file.\n";
    return 1;
  }

  n = atol(argv[2]) - 1;

  for(i=0, j=n; i < j; ++i, --j) {
    finout.seekg(i, ios::beg);
    finout.get(ch1);
 
    finout.seekp(j, ios::beg);
    finout.put(ch1);

    if(!finout.good()) {
      cout << "Error reading or writing characters.";
      finout.clear();
      break;
    }
  }
  finout.close();

  if(!finout.good()) {
    cout << "A file error occurred.";
    return 1;
  }

  return 0;
}
  
    
  








Related examples in the same category

1.fstream seekp: Seek file pointer position
2.Reverse file content
3.Demonstrate File random access.
4.To read or write to a file, you include
5.File Stream Objects as Function Arguments