Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define MAX 40
#define MAXN 10
struct List {
char name[MAX];
int grade;
char lettergrade[MAXN];
};
FILE * OpenFile ( char [], char []);
int GetList (FILE *, struct List []);
void SortList(struct List[], const int);
void DisplayList (const struct List [], const int);
int main (void)
{
struct List students[MAX] = { };
int size;
FILE * fptr = OpenFile("textfile","r");
size = GetList(fptr, students);
fclose(fptr);
printf("Unsorted Records: \n");
DisplayList (students, size);
printf("\n\nSorted Records: \n");
SortList(students,size);
DisplayList(students,size);
printf("\n\nYou Figure Out The Rest");
return 0;
}
FILE * OpenFile(char filename[], char m [])
{
//open the file
FILE *fptr = fopen(filename, m);
//validate the file pointer
if (fptr == NULL) exit(1);
return fptr;
}
int GetList (FILE *fptr, struct List a[])
{
int count = 0;
char buffer[256];
//Take one line from the datfile and place it into a buffer
while ( fgets(buffer, 256, fptr) != NULL )
{
if (!isdigit(buffer[0]))
{
//Extract data from buffer into structure array members
sscanf(buffer, "%s", a[count].name);
continue;
}else
sscanf(buffer, "%d", &a[count].grade );
count++;
}
//return number of records read
return count;
}
void SortList(struct List a[], const int size)
{
int i, ii;
struct List temp;
for ( i = 0; i < size; i++)
{
for(ii = i+ 1; ii < size; ii++)
{
if( a[i].grade < a[ii].grade)
{
//switch structure indexes
temp = a[i];
a[i] = a[ii];
a[ii] = temp;
}
}
}
}
void DisplayList (const struct List a[], const int size)
{
int i;
for( i = 0; i < size; i++)
printf("%s %d\n", a[i].name, a[i].grade);
}
Try that. Only a couple changes, however that datafile is problematic because it is not organized into records. I would not have used a structure at all had I known beforehand the organization of the datafile.