I am trying to make an information system but whenever I try and print the output, it only prints out the last thing I enter. Here is the function I am using.
void displayStudents(){
FILE *fp;
fp = fopen("studentlist.txt", "rb");
if(!fp){
printf("File could not be opened.\n");
}else{
studentInfo s;
while(fread(&s, sizeof(studentInfo), 1, fp) && !feof(fp)){
printf("Student Number: %i\n", s.studentNumber);
printf("Last Name: %s\n", s.lastName);
printf("First Name: %s\n", s.firstName);
printf("Course: %s\n", s.course);
printf("Year Level: %i\n", s.yearLevel);
printf("Age: %i\n", s.age);
printf("Sex: %c\n", s.sex);
printf("Final Grade: %i\n", s.finalGrade);
printf("\n\n");
}
fclose(fp);
}
}
Where studentInfo
is a struct containing the following...
struct studentInfo{
int studentNumber;
char lastName[15];
char firstName[15];
char course[15];
int yearLevel;
int age;
char sex;
int finalGrade;
};
typedef struct studentInfo studentInfo;
The output of the program is as follows:
Student Number: 0
Last Name:
First Name:
Course:
Year Level: 0
Age: 0
Sex:
Final Grade: 0
Student Number: 0
Last Name:
First Name:
Course:
Year Level: 0
Age: 0
Sex:
Final Grade: 0
Student Number: 3
Last Name: Rambo
First Name: Ra
Course: CS
Year Level: 1
Age: 10
Sex: F
Final Grade: 89
I tried enrolling 3 students but it only prints out information for the last and not the ones before. I want it to be able to display all student info I input.
I realized I was placing binary in the file and was only reading it as a .txt
so it never worked out. Thats why I merely changed my file type to .bin
from .txt
that way it would read and it did. I was also reading a bin file normally like any other text when i should have done rb
. My bad.