Ok, I'm filling up the array correctly. Now I need to qsort and then do a binary search on it. However, I'm having difficulty using bsearh. Here is my code:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_PERSON 100
#define MAX_NAME 10
struct person {
char name[MAX_NAME];
int num;
};
int compare(const void *p, const void *s) {
return strcmp(((struct person*)p)->name, ((struct person*)s)->name);
}
int compare2(const void *p, const void *s) {
return strcmp((char *)p, ((struct person*)s)->name);
}
main(int argc, char *argv[]) {
char buf[BUFSIZ];
char *tok;
char *result;
char lookup[3];
int lineNum = 1;
int pos = 0;
int i;
FILE *fp;
struct person people[MAX_PERSON];
struct person *match;
while ( fgets(buf,BUFSIZ,stdin) != NULL ) {
tok = strtok(buf," ");
strcpy(people[pos].name,tok);
people[pos].num = lineNum;
pos++;
tok = strtok(NULL,"\n");
strcpy(people[pos].name,tok);
people[pos].num = lineNum;
pos++;
lineNum++;
}
qsort(people,pos,sizeof(struct person), compare);
if ( (fp = fopen(argv[1],"r")) == NULL) {
fprintf(stderr,"Cannot open %s\n",argv[1]);
exit(1);
}
while ( fgets(buf,BUFSIZ,fp) != NULL ) {
tok = strtok(buf," ");
strncpy(lookup,tok,3);
match = (struct person*)bsearch(lookup,people,pos,sizeof(struct person),compare2);
printf("%s",match->name);
}
for (i = 0; i < pos; i++) {
printf("%s %d\n", people[i].name,people[i].num);
}
}
I have no idea if I'm using bsearch right or not. What I want to do is take lines from a file like this:
Ann: Ken Jim Ian Len
Bev: Len Ian Jim Ken
Cat: Ken Ian Jim Len
Dot: Ian Len Ken Jim
Ian: Bev Cat Ann Dot
Jim: Dot Cat Ann Bev
Ken: Bev Cat Ann Dot
Len: Dot Bev Ann Cat
Then I want to bsearch through my people array and get the number that goes with that person. Can someone tell me how to use bsearch right? I know I'll have to use strtok more than once in the second while loop, but I was just testing bsearch. I'm getting a segmentation fault at the moment.