Code:
#include <stdio.h>
#include <stdlib.h>
#define MAXITEM 2000
#define maxN 10
typedef int Key;
typedef struct
{
char *sname;
char *lname;
char phone[maxN];
} Item;
Item NULLitem = {"","",-1};
int eq(Key k1,Key k2){
return k1 == k2;
}
int less(Key k1, Key k2){
return k1 < k2;
}
Key key(Item item){
return item.phone;
}
typedef struct STnode* link;
struct STnode{
Item item;
link left;
link right;
int N;
};
static link head,z;
void STinit()
{ head =(z = NEW(NULLitem,0,0,0));}
link NEWnode(Item item, link left, link right){
link x =malloc(sizeof *x);
if (x==NULL){
printf("error allocating memory.\n");
exit(EXIT_FAILURE);
}
x->item =item;
x->left =left;
x->right =right;
return x;
}
static link root;
Item search(link x, Key k){
if(x == NULL)
return NULLitem;
else if (eq(k, key(x->item))
return x->item;
else if (less(k,key(x->item))
return search(x->left,k)
else
return search(x->right,k);
}
Item STsearch(Key k){
return search(root,k);
}
link insert(link x,Item item){
if (x==NULL)
return NEWnode(item, NULL, NULL);
else if (less(Key(item), key(x->item))
x->left = insert(x->left,item);
else
x->right = insert(x->righ, itm);
return x;
}
void STinsert(Item item ){
head = insert(root, item);
}
void usage( char *progname )
/***************************/
{
fprintf( stderr,
"Usage: %s \"source-file\"\n",
progname );
exit( EXIT_FAILURE );
}
int main (int argc, char *argv[])
{
FILE *stream;
Item records[MAXITEM];
int indices[MAXITEM];
int i,count = 0, x , y,t,N=0;
char temp_sname[100];
char temp_lname[100];
char query[10];
char *v;
if (argc != 2)
usage (argv[0]);
if( (stream = fopen( argv[1], "r" )) != NULL )
{
while( !feof( stream ) )
{
if ( fscanf( stream, "%s\t%s\t%d", temp_sname, temp_lname, records[count].phone ) != 3 )
break;
if( (records[count].sname = malloc( strlen( temp_sname ) + 1 )) != NULL )
{
strcpy( records[count].sname, temp_sname );
}
if( (records[count].lname = malloc( strlen( temp_lname ) + 1 )) != NULL )
{
strcpy( records[count].lname, temp_lname );
}
i++;
if (count >= MAXITEM)
{
fprintf(stderr,"too many items\n");
exit (1);
}
}
STinit(maxN);
for (i=0;i<N;i++) STinsert(records[i]);
while (gets(query)!=NULL)
if(!null(v=STsearch(query)))
printf("%s\n", query);
else printf("(not found) %s\n",query);
}
else
{
printf( "Problem opening the file\n" );
}
}