All pastes #56005 Raw Edit

Unnamed

public c v1 · immutable
#56005 ·published 2006-05-15 18:24 UTC
rendered paste body
#include <stdio.h>#include <errno.h>#include <stdlib.h> struct  employee {	char lastname[30];	char firstname[30];	int emp_id;	time_t start_date;};/* emp_id_compare --- compare by ID */ int emp_id_compare(const void *e1p, const void *e2p) {	const struct employee *e1, *e2;		e1 = (const struct employee *) e1p;	e2 = (const struct employee *) e2p;		if (e1->emp_id < e2->emp_id) return -1;	if (e1->emp_id > e2->emp_id) return 1;	else return 0;}/* print_employee() --- print employee-structure */ void print_employee(const struct employee *emp) {	printf("%s %s\t%d\t%s", emp->lastname, emp->firstname, emp->emp_id, ctime(emp->start_date));}/* main --- demonstarte sorting and bsearching */ int main(int argc, char **argv) {#define NPRES 10	char *myname = argv[0];	struct employee presidents[NPRES];	int i, npres;	char buf[BUFSIZ];	struct employee *the_pres; /* pointer-variable for found-item */  	struct employee key; /* structure for search-criteria 	*/	int id; /* what we want to search for */ 	FILE *fp; /* we need a file for president-data, because we use stdin to prompt for the DI */ 		/* check for arguments */ 	if (argc != 2) {		fprintf(stderr, "usage: %s filename\n", myname);		exit(1);	}		/* Open the file */ 	if ((fp = fopen(argv[1], "r")) == NULL) {		fprintf(stderr, "%s: %s: could not open: %s", myname, argv[1], strerror(errno));		exit(1);	}		/* read data from file */ 	for (npres = 0; (npres < NPRES) && fgets(buf, BUFSIZ, fp) != NULL; npres++) {		sscanf(buf, "%s %s %ld %ld", presidents[npres].lastname, presidents[npres].firstname,			presidents[npres].emp_id, presidents[npres].start_date);	}		/* close the file */ 	fclose(fp);		/* npres is now the number of president-items read */ 		/* Sort presidents by id */ 	qsort(presidents, npres, sizeof(struct employee), emp_id_compare);		/* print sorted array */ 	printf("Sorted by ID:\n");	for (i = 0; i<npres; i++) {		putchar('\t');		print_employee(&presidents[i]);	}		/* infinite searching loop */ 	for (;;) {		printf("Enter ID: ");		if (fgets(buf, BUFSIZ, stdin) == NULL) break; /* read from stdin and exit on EOF */ 		sscanf(buf, "%d\n", &id);				key.emp_id = id; /* set search-criteria */ 				/* set the_pres pointer to the pointer returned by bsearch() */  		the_pres = (struct employee *) bsearch(&key, presidents, npres, sizeof(struct employee), emp_id_compare);				if (the_pres != NULL) {			printf("Found: ");			print_employee(the_pres);		}		else {			printf("Employee with ID %d not found!\n", key.emp_id);		}	}	putchar('\n'); /* A final new line on EOF */	exit(0);   }