L
lovecreatesbeauty
$ cat bse*
The bsearch call in below code doesn't find the correct record. When I
specify the name ie. "andrew" as the search key, it shows me with the
record "andrew 5000". Where am I wrong?
Thank for your time.
/************************************ 80 x
*************************************
* read lines from text file, bsearch by name then show whole line
containing
* the specified name. text file shows below:
*
* jack 100000
* bach 1 mil.
* andrew 5000
* michael 11222
************************************* 80 x
************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
#define LEN 128
int compar(const void *a, const void *b);
int main(int argc, char *argv[])
{
FILE *file;
char buf[N][LEN] = {'\0'};
int n_cnt = 0;
char *p = NULL;
if (argc != 3){
printf("Usage: %s <input_file> <key>\n", argv[0]);
return -1;
}
file = fopen(argv[1], "r");
if (!file){
printf("\"%s\" fopen error\n", argv[1]);
return -1;
}
while (n_cnt < N && fgets(buf[n_cnt++], LEN - 1, file));
fclose(file);
qsort(buf[0], N, LEN, compar);
if (p = bsearch(argv[2], buf[0], N, LEN, compar))
printf("Found: %s:%d\n", p, strlen(p));
else
printf("Not Found\n");
return 0;
}
int compar(const void *a, const void *b)
{
const char *pa = a;
const char *pb = b;
int len_a = strlen(pa);
int len_b = strlen(pb);
int len = len_a < len_b ? len_a : len_b;
return (strncmp(a, b, len));
}
$
The bsearch call in below code doesn't find the correct record. When I
specify the name ie. "andrew" as the search key, it shows me with the
record "andrew 5000". Where am I wrong?
Thank for your time.
/************************************ 80 x
*************************************
* read lines from text file, bsearch by name then show whole line
containing
* the specified name. text file shows below:
*
* jack 100000
* bach 1 mil.
* andrew 5000
* michael 11222
************************************* 80 x
************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
#define LEN 128
int compar(const void *a, const void *b);
int main(int argc, char *argv[])
{
FILE *file;
char buf[N][LEN] = {'\0'};
int n_cnt = 0;
char *p = NULL;
if (argc != 3){
printf("Usage: %s <input_file> <key>\n", argv[0]);
return -1;
}
file = fopen(argv[1], "r");
if (!file){
printf("\"%s\" fopen error\n", argv[1]);
return -1;
}
while (n_cnt < N && fgets(buf[n_cnt++], LEN - 1, file));
fclose(file);
qsort(buf[0], N, LEN, compar);
if (p = bsearch(argv[2], buf[0], N, LEN, compar))
printf("Found: %s:%d\n", p, strlen(p));
else
printf("Not Found\n");
return 0;
}
int compar(const void *a, const void *b)
{
const char *pa = a;
const char *pb = b;
int len_a = strlen(pa);
int len_b = strlen(pb);
int len = len_a < len_b ? len_a : len_b;
return (strncmp(a, b, len));
}
$