CS44: Database Management Systems

Example use of the FileScanner class

/****EXAMPLE USE OF FILESCANNER CLASS******/
void exampleFileScanner(std::string filename){
  // Clean up from any previous runs that crashed.
  {
    // Create a new database file.
    PageFile new_file = PageFile::create(filename);

    // Allocate some pages and put data on them.
    for (int i = 0; i < 20; ++i) {
      RECORD record;
      PageId new_page_number;
      Page new_page = new_file.allocatePage(new_page_number);

      sprintf(record.s, "%05d string record", i);
      record.i = i;
      record.d = (double)i;
      std::string new_data((char*)(&record), sizeof(record));

      new_page.insertRecord(new_data);
      new_file.writePage(new_page_number, new_page);
    }

  }
  // new_file goes out of scope here, so file is automatically closed.

  { //Demonstrate how to use FileScanner to read relational data
    FileScanner fscan(filename, bufMgr);

    try {
      RecordId scanRid;
      while(true) {
        //get the record (as c-string)
        fscan.scanNext(scanRid);
        std::string recordStr = fscan.getRecord();
        const char *record = recordStr.c_str();
        //extract the integer field
        int key = *((int *)(record + offsetof(RECORD, i)));
        std::cout << "Extracted : " << key << std::endl;
      }
    } catch(EndOfFileException e) {
      std::cout << "Read all records" << std::endl;
    }
  }
  // filescan goes out of scope here, so relation file gets closed.

  File::remove(filename);
}
/******************************************************************/