This solution processes student records from a file, sorts them by GPA, and generates a report.
students.txtAlice 1001 3.8
Bob 1002 3.9
Charlie 1003 3.5
Diana 1004 3.7
Eve 1005 4.0
output.txtSorted Students (by GPA):
Eve 1005 4.00
Bob 1002 3.90
Alice 1001 3.80
Diana 1004 3.70
Charlie 1003 3.50
Average GPA: 3.78
Top Student: Eve (4.00)
#include <stdio.h>
#include <string.h>
struct Student {
char name[50];
int id;
float gpa;
};
This function reads student data from the input file.
int readStudents(FILE* fp, struct Student* students) {
int count = 0;
// Read until end of file or array is full
while (fscanf(fp, "%s %d %f", students[count].name,
&students[count].id,
&students[count].gpa) == 3) {
count++;
if (count >= 100) { // Safety limit
break;
}
}
return count;
}
Explanation:
fscanf() returns the number of items successfully read