Public feed #602078

Miscellany

public text v1 · immutable
Raw Edit
·published 2007-07-03 21:39 UTC
rendered paste body
#include <stdio.h>
#include <stdlib.h>
#define MAX 28

/* Student Structure */
	struct student {
		int id;
	      float mt;
	      float final;
	} Student[MAX];

typedef int (*compfn)(const void*, const void*);
void printarray(void);
int compare(struct student *, struct student*);

int main(void)
{

	/* Declare Variables */
	FILE * record;
	FILE * backup;
	char input[MAX];
	static int i = 0;
	int j, inputid;
	

	/* Open file for reading */
	if ((record = fopen("/home/nate/code/jawn/record", "r")) == NULL) {
		printf("Error opening record file");
		exit(-1);
	} 
	
	/* Get lines and parse them */
	while ( fgets( &input, MAX, record) != NULL) {
		sscanf(&input, "%d %f %f", &Student[i].id, 
		&Student[i].mt, &Student[i].final);
		i++;
	}
	
	
	/* Sort the structure */
	qsort((void *)&Student, i, sizeof(struct student), (compfn)compare);
	
	/* Open file for writing */
	if ( (backup = fopen("/home/nate/code/jawn/backup", "a")) == NULL ) {
		printf("Failed opening backup file");
		exit(-1);
	}
	
	/* Write output */
	int k;
	struct student * destination;
	for (k = 0; k < i; k++)
		fprintf( backup, "%d %.1f %.1f\n",
			 Student[k].id, Student[k].mt, Student[k].final);
	
	/* Search for Student ID */
	printf("Please Enter a student id to search for:");
	
	while ( (scanf("%d", &inputid) == 1) && (inputid >= 0)) { //While input != -numbers
		
		if ( (destination = 
			bsearch(&inputid,
				&Student, 
				i, 
				sizeof(struct student),
				 compare)) == NULL) { //If not found
			printf("ID %d Not Found.\n", inputid);
		} else { //It was found
		  	printf("Student ID %d mt = %f final = %f\n", 
				destination->id, destination->mt, destination->final);
		}
		printf("\n Enter a student id to search: "); //Enter loop again
	}
	return 0;		
}

int compare(struct student *elem1, struct student *elem2) {
    if ( elem1->id < elem2->id)
	return -1;
    else if (elem1->id > elem2->id)
	return 1;
    else
	return 0;
}

void printarray(void){
	int i;
	
	for (i = 0; i < 5; i++)
		printf("%d: Score %.1f %.1f\n", 
		       Student[i].id, Student[i].mt, Student[i].final);
}