Sunday, April 8, 2012

Break down of the Fstream walkthrough in class:

#include <fstream>
#include <iostream>
using namespace std;
int main(){
  int i,j;
  cout<<sizeof(i)<<endl;   // the output of this line is 4
  fstream f("f.bin",ios::out|ios::in|ios::binary|ios::trunc);
  for(i=10;i<100;i+=10){//write 10,20,30...90
    f.write((const char*)&i, sizeof(int)); //casting &i to char* because you cannot convert a char with a int because char are 1 byte whilst int are 4 bytes
                                          //hence turning it to char* and &i will make both variable to 4 bytes (all pointers are 4 bytes)
                                          //we put sizeof(int) because we want to write 4 bytes because we want to keep the number in the file as int not char hence keeping the right number
  }
  f.seekg((ios::pos_type)20);//going to position 20 in bytes(since in the file each number is an integer (4 bytes) it will shift 5 numbers (20/4)), casting 20 as a pos_type
  f.read((char*)&i, sizeof(int));//reads sizeof(int)(4 bytes) and store it in i
  cout<<i<<endl; // 1 mark //output is 60, even though its on position 50 it reads number after the position not the position itself
  f.seekg(-(ios::off_type)sizeof(int), ios::end);//go back 4 bytes from the end of the file,at position is at 80
  f.read((char*)&i, sizeof(int));//read the next 4 byte and store it in i
  cout<<i<<endl; // 1 mark output: 90.
  f.seekg(-(ios::off_type)sizeof(int)*3, ios::cur);//go back 12(4*3) bytes(3 ints) from the current position(90), at position(60)
  f.read((char*)&i, sizeof(int));
  cout<<i<<endl; // 1 mark output:70
  f.seekp((ios::off_type)sizeof(int)*2, ios::beg);//go up 8 bytes from the beginnning of the file position(20)
  f.write((char*)&i, sizeof(int));//write 4 bytes from &i(holding number 70 from previous read function)
  f.seekp((ios::off_type)0, ios::end);//change the writing position to the end of the file
  cout<<(j=f.tellp())<<endl;  // 1 mark, j=36 because there are 9 integer in the file hence 36 bytes in total (4*9)
  f.seekg(0);//put the reading cursor to position 0
  while(f.tellg() < j){  // 1 mark, read one integer at a time until the f.tellg() is less than j
    cout << "("<<f.tellg() <<")";
    f.read((char*)&i, sizeof(int));
    cout<<i<<"("<<f.tellg() << "), ";
  }
  //output: (0)10(4), (4)20(8), (8)70(12), (12)40(16), (16)50(20), (20)60(24), (24)70(28), (28)80(32), (32)90(36),
  cout<<endl;   
  return 0;
}

No comments:

Post a Comment