/*

============================================================================

Name        : bsearch.c

Author      : SeYUN

Version     :

Copyright   : Your copyright notice

Description : Hello World in C, Ansi-style

============================================================================

*/

#include <stdio.h>

#include <stdlib.h>

#include <search.h>

#include <string.h>

/* 고객정보 Node 단위 */

typedef struct _Customer {

char cust_no[10+1];

char name[50+1];

int age;

char tel[25+1];

}Customer;

/* 비교 연산자 */

int cust_compare(const Customer *one, const Customer *other) {

return strncmp(one->cust_no, other->cust_no, sizeof(one->cust_no) - 1);

}

int main(void) {

Customer table[1000] = {0,}; /* 중복 불가 데이터 */

Customer table2[1000] = {0,}; /* 중복 가능 데이터 */

FILE *fp = NULL;

//char buf[512];

Customer temp = {0,};

Customer *p_cust = NULL;

size_t total_cn = 0; /* 중복불가 테이블 자료 건수 */

size_t total_cn2 = 0; /* 중복가능 데이틀 자료 건수 */

if ( fp = fopen("./cust.dat", "r")) {

while( 0< fscanf(fp, "%s %s %d %s", temp.cust_no, temp.name, &temp.age, temp.tel)) {

/*------------------------------------------------------------------------------------------------*/

/* 1. Key중복을 제거 해야 하는 중우 lsearch를 사용 여기서는 별도의 건수초과는 체크 하지 않음 */

//lfind는 검색만 lsearch는 없으면 추가까지 해줌 단, 중복데이터가 발생 할 수 있는 경우에는 별도의 입력 알고리즘을 생각해야 함

p_cust = (Customer *)lsearch(temp.cust_no, table, &total_cn, sizeof(Customer), cust_compare);

/* Key 중복일 경우에는 별도로 마지막에 넣어준다. */

/* 2. Key중복이 있는 데이터일 경우 강제 입력. 여기서는 별도의 건수초과는 체크 하지 않음 */

memcpy(&table2[total_cn2], &temp, sizeof(Customer) );

total_cn2++;

/* bsearch를 위해 정렬 맨날 입력할 때 마다 정렬..비합리 비효율 ㅋㅋ*/

qsort(table, total_cn, sizeof(Customer), cust_compare);

qsort(table2, total_cn2, sizeof(Customer), cust_compare);

}

}

for(int i = 0 ; i < 100 ; i++ ) {

printf("[%d] , cust: [%s],[%s],[%d],[%s]\n", i, table[i].cust_no, table[i].name, table[i].age, table[i].tel);

}

printf("-----------------------------------------------------------------------\n");

for(int i = 0 ; i < 100 ; i++ ) {

printf("[%d] , cust: [%s],[%s],[%d],[%s]\n", i, table2[i].cust_no, table2[i].name, table2[i].age, table2[i].tel);

}

/* bsearch를 통해 데이터 감색 단, 검색데이터는 오름차순으로 정렬되어 있어야 한다. */

p_cust = NULL; /* 초기화 */

const char *p = "A000000002";

p_cust = (Customer *)lfind(p, table2, &total_cn2, sizeof(Customer), cust_compare);

if( p_cust == NULL ) {

printf("%s key 값의 데이터는 없습니다.\n", p);

}else{

printf("찾은 값 : cust: [%s],[%s],[%d],[%s]\n", p_cust->cust_no, p_cust->name, p_cust->age, p_cust->tel);

do {

p_cust++;

if(strncmp(p, p_cust->cust_no, sizeof(p_cust->cust_no) - 1) == 0) {

printf("찾은 값 : cust: [%s],[%s],[%d],[%s]\n", p_cust->cust_no, p_cust->name, p_cust->age, p_cust->tel);

}

} while(strncmp(p, p_cust->cust_no, sizeof(p_cust->cust_no) - 1) == 0);

}

return EXIT_SUCCESS;

}
























+ Recent posts