Sunday, April 15, 2012

Test 2 Q4 walkthrough with comments!


Q4:

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
struct PhRec{
  char name[60];
  int PhoneNumber;
};
bool operator<(PhRec& left, PhRec& right){
  return strcmp(left.name, right.name) < 0;
}
#include "tqueue.h"

int main(){
  fstream f("phones.bin", ios::in|ios::binary);//just reads the file
  PhRec pr;
  Tqueue<PhRec> Q;//change all Tqueue type into PhRec type
  while(f.good()){//continue in this loop if f.good() is true
    f.read((char*)&pr, sizeof(pr));//reads the sizeof(pr) and store it in &pr as a char*
    if(f.good()){//if the previous read function worked go in here
      Q.append(pr);//append pr (in this case is a character string) to the queue list
    }
  }
  f.close();
  f.open("phones.bin", ios::out|ios::binary);//rewriting the file
  Q.sort(true);//sort the Queue list
  while(!Q.isEmpty()){//continue this loop until the Queue list is empty
    pr = Q.remove();//assign pr with the value of Q.remove();
    f.write((const char*)&pr, sizeof(pr));//write sizeof(pr) bytes from &pr as a char*
  }
  return 0;
}

1 comment: