Tuesday, 9 April 2013

Backward Binary Print with seekg and ios::cur


#include <iostream>
#include <fstream>
using namespace std;

int main(){
  int i;
  int loc;
  fstream file("output.bin", ios::in|ios::binary);
  while(!file.fail()){
    file.read((char*)&i, sizeof(i));
    if(!file.fail()){
      cout<<i<<", ";
    }
  }
  cout<<endl;
  file.clear();
  cout<<(loc = file.tellg())<<endl;
  loc -= sizeof(int);
  while (loc >= 0){
    file.seekg((ios::pos_type)loc);
    file.read((char*)&i, sizeof(i));
    cout<<i<<", ";
    loc -= sizeof(int);
  }
  file.seekg((ios::off_type)0, ios::end);
  while(file.tellg()) {
    file.seekg((ios::off_type)-(signed)sizeof(int), ios::cur);
    file.read((char*)&i, sizeof(i));
    cout<<i<<", ";
    file.seekg((ios::off_type)-(signed)sizeof(int), ios::cur);
  }
  return 0;
}

No comments:

Post a comment