/* * Demo of reading a file into an array of records */ #include #include typedef struct { char name[20]; /* frog name */ double height; /* high jump in inches */ int bestTime; /* race time in seconds */ int rank; /* ranking */ } frog_t; void readFile(frog_t list[], int *numFrogs); void displayResults(const frog_t list[], int numFrogs); int main(void) { int numFrogs; frog_t list[50]; /* the list of frogs */ readFile(list, &numFrogs); displayResults(list, numFrogs); return 0; } /* Read the data into the array */ void readFile(frog_t list[], /* output - array of frogs */ int *numFrogs) /* output - number of frogs */ { FILE *inp = NULL; int input_status; int idx = 0; inp = fopen ("frog.data", "r"); input_status = fscanf(inp, "%s %lf %d %d", list[idx].name, &list[idx].height, &list[idx].bestTime, &list[idx].rank); while (input_status != EOF) { idx++; input_status = fscanf(inp, "%s %lf %d %d", list[idx].name, &list[idx].height, &list[idx].bestTime, &list[idx].rank); } *numFrogs = idx; } /* Display the frog data */ void displayResults(const frog_t list[], /* input - frog list */ int numFrogs) /* input - number of frogs in the list */ { int idx; printf ("\t\tFrog Report:\n"); printf ("Name Height Time Rank \n"); printf ("----------------------------------------------\n"); for (idx = 0; idx < numFrogs; idx++) { printf ("%-18s%7.2f", list[idx].name, list[idx].height); printf (" %4d %2d\n", list[idx].bestTime, list[idx].rank); } }