Something like this might do the trick for you;
#include<stdio.h>
#include<stdlib.h>
typedef struct {
char name[100];
int gradeA;
int gradeB;
int gradeC;
} student;
student* read_student(FILE* file) {
student* s = (student*)malloc(sizeof(student));
if (fscanf(file,"%s %d %d %d", &s->name, &s->gradeA, &s->gradeB, &s->gradeC) != EOF) {
return s;
}
else {
free(s);
return NULL;
}
}
void print_student(student* s) {
printf("%s %d %d %d\r\n", s->name, s->gradeA, s->gradeB, s->gradeC);
}
int main() {
FILE* file = fopen("C:\\Temp\\grades.txt", "r");
student* s = NULL;
student** students;
int count = 0;
while((s = read_student(file))) {
student** new_students = (student**)malloc(sizeof(student) * (count + 1));
for(int i = 0; i < count; ++i) {
new_students[i] = students[i];
}
new_students[count] = s;
free(students);
students = new_students;
++count;
}
fclose(file);
for(int i = 0; i < count; ++i) {
print_student(students[i]);
}
return 0;
}
Instead of
realloc
I've just dumped the old list and created a new every time.
I would recommend using a some form of linked list structure to track each student read instead.
Hope this helps,
Fredrik