Slide 13.7: InsertBook.h
Slide 13.9: FindBook.cpp
Home

InsertIndex.h


This code is to update the index index.txt . Again, since the index is kept in sorted order by key, insertion of the new index entry probably requires some rearrangement of the index. We have to shift or slide all the entries with keys that come in order after the key of the record we are inserting. The shifting opens up a space for the new entry.

This program performs the following tasks according to the program control flow:
  1. If the index contains no entries, simply write the newly created entry to the index.
  2. Sequentially read the index entries until the key value is greater than or equal to the new key or end of file is reached. In the meantime, write the entries just read to a temporary index.

    • If the key value is greater than or equal to the new key, write the new entry and the remaining file to the temporary index.
    • If the end of file is reached, write the new entry to the end of the temporary index.

  3. Replace the index by the temporary index.
 ~wenchen/public_html/cgi-bin/351/week13/InsertIndex.h 
#include  <fstream>
#include  <iostream>
#include  <cstdlib>
#include  <cstring>
  using namespace  std;

#include  "FixedLen.h"
void InsertIndex( char* ISBN, int offset ) {
  fstream  index, temp;
  int      number, length, result;
  char     str[256], buffer[1024];
  bool     found = false, duplicate = false;
  index.open( "index.txt", fstream::out | fstream::in );
  index.read( str, 6 );
  if ( ( number = atoi( str ) ) == 0 ) {
    index.seekp( 12, fstream::beg );
    index << ISBN << '|' << FixedLen( offset, str, 5 ) << endl;
    index.seekp( 0, fstream::beg );
    index << FixedLen( 1, str, 6 );
    index.close( );
    return;
  }
  temp.open( "temp.txt", fstream::out );
  temp << FixedLen( number+1, str, 6 );
  index.read( str, 6 );
  length = atoi( str );
  temp.write( str, 6 );
  for ( int i = 0;  i < number && !found;  i++ ) {
    index.read( str, length );
    if ( ( result = strncmp( ISBN, str, 10 ) ) > 0 )
      temp.write( str, length );
    else {
      if ( result == 0 )  duplicate = true;
      temp << ISBN << '|' << FixedLen( offset, buffer, 5 ) << endl;
      temp.write( str, length );
      do {
        index.read( buffer, 1024 );
        length = index.gcount( );
        temp.write( buffer, length );
      } while ( !index.eof( ) );
    found = true;
   }
  }
  if ( !found )
    temp << ISBN << '|' << FixedLen( offset, buffer, 5 ) << endl;
  if ( duplicate )
    cout << "\n\nDuplicate ISBN: " << ISBN << "\n\n";
  system( "mv temp.txt index.txt" );
  index.close( );
  temp.close ( );
}