Hello,
I'm currently working on an assignment where I have to take in names from stdin, put them in an array of structs (where each struct has a name and a number), and then qsort that array. Then, I have to use bsearch to search for names (from a file provided as a command-line argument) and then output the number associated with the name. 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 seem to be getting a segmentation fault from the printf statement in the while loop. That is just there for testing purposes. Am I even using bsearch correctly? My compare2 function might be incorrect, but I don't even know if the whole thing is correct. Please help! Oh, I used strncpy with 3 because each name will only have 3 letters in them and the lines of names from the CLA file have the first name as Ann: Bill Bob and so on. So, I used strncpy to get rid of the colon and any end of line characters.