Slide 7.3: Variable-length record addition demonstrations (cont.)
Slide 7.5: FixedLen.h
Home

EnterBook.cpp


This is the main routine for the button of Enter books of the second interface of the previous slide. It performs the following tasks:
  1. Reads book data from the Web and composes a record for the data.
  2. Starts searching the avail list sequentially until it finds the first slot which is large enough to store the new record.
  3. If a slot is found, the record is inserted to there and the links in the avail list are adjusted accordingly.
  4. If no slots are found, the record is appended to the end of the file.
 ~wenchen/public_html/cgi-bin/351/week7/EnterBook.cpp 
#include  <fstream>
#include  <iostream>
#include  <cstring>
  using namespace  std;

#include  "FixedLen.h"
#include  "Record.h"
#include  "Append.h"
int  main( int argc, char* argv[ ] ) {
  char     str[10], bar;
  char     spaces[128] = "                                                  ";
  int      avail, prev, curr, next, last;
  int      len, size, offset;
  bool     found, head;
  Record   r;
  fstream  file;
  file.open( "books.txt", fstream::in|fstream::out );
  r.ReadData( argv[1], argv[2], argv[3], argv[3] );
  len = r.GetSize( );
  file >> avail >> last;
  prev = curr = next = avail;
  head = true;  found = false;
  while ( ( next != -1 )  && !found ) { 
    file.seekg( curr, fstream::beg );
    file >> size >> offset;
    file.get( str, 10, '|' );
    file >> bar >> next;

    if ( size > len ) {
      found = true;
      file.seekp( curr+12, fstream::beg );
      file <<  r.GetBuf( );
      file.write( spaces, size-len-1 );
      file << '\n';
      if ( head ) {
        file.seekp( 0, fstream::beg );
        file << FixedLen( next, str, 5 );
      }
      else {  
        file.seekg( prev+14, fstream::beg );
        file << FixedLen( next, str, 6 );
      }
    }
    prev = curr;  curr = next;  head = false;
  }

  if ( !found )  r.Append( file5 );
  file.close( );
}