#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAME_SIZE 32
#define TEL_SIZE 15
#define FNAME 128
#define BUF_SIZE 128
struct Rec
{
char nameLast[NAME_SIZE];
char nameFirst[NAME_SIZE];
char Tel[TEL_SIZE];
};
struct INDX
{
char nameLast[NAME_SIZE];
char nameFirst[NAME_SIZE];
fpos_t offset;
};
void find_index_entry( INDX *ptr );
Rec *read_entry_rec( const fpos_t *pos);
int main ( void )
{
INDX data; Rec *entry; printf( "\n\nEnter 'quit' for the last name to quit the program.\n\n" );
while ( true )
{
data.offset = -1;
printf( "\nPlease enter the last name: " );
if ( fgets(data.nameLast, NAME_SIZE, stdin) == NULL ) return EXIT_FAILURE;
else
data.nameLast[strlen(data.nameLast)-1]='\0';
if ( !strcmp(data.nameLast,"quit") )
break;
printf( "\nPlease enter the first name: " );
if ( fgets(data.nameFirst, NAME_SIZE, stdin) == NULL ) return EXIT_FAILURE;
else
data.nameFirst[strlen(data.nameFirst)-1]='\0';
printf( "\n\nSearching...\n\n" );
find_index_entry( &data );
if ( data.offset == -1 )
printf( "\n\nNo one was found under '%s %s'.\n", data.nameFirst, data.nameLast );
else
{
if ( (entry = read_entry_rec(&data.offset) ) == NULL )
{
printf( "\n\nFailed to lookup entry.\n\n" );
continue;
}
printf( "\n\nFound!\n----------\n%s,%s -> %s\n----------\n", entry->nameFirst,entry->nameLast, entry->Tel);
free(entry);
entry = NULL;
}
}
printf( "\n\nThank you, good bye!\n\n" );
}
Rec *read_entry_rec( const fpos_t *pos)
{
Rec *ptr = NULL;
FILE *f = fopen( "output.txt", "r" ); if ( !f )
return NULL;
if ( fsetpos(f, pos) != 0 )
return false;
ptr = (Rec*)malloc(sizeof(Rec));
fread(ptr, sizeof(struct Rec), 1, f);
fclose(f);
return ptr;
}
void find_index_entry( INDX *ptr )
{
INDX temp; bool found = false; FILE *index_file = fopen( "index", "r" );
if ( !index_file )
return;
while ( !found )
{
if ( fread(&temp, sizeof(struct INDX), 1, index_file) == 0 )
return;
if ( !strcmp(ptr->nameLast, temp.nameLast) && !strcmp(ptr->nameFirst, temp.nameFirst) )
{
ptr->offset = temp.offset;
found = true;
}
}
fclose(index_file); }