Mega Code Archive

 
Categories / C++ / File
 

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; }