The purpose of the following code is to read data from a file on disk:
#include<stdio.h>
#include<stdlib.h>
struct Student {
int number;
char name[4];
int age;
char sex[6];
float score;
};
struct Student student[10];
int main()
{
FILE *hzh;
int i;
if ((hzh = fopen("huangzihan.txt", "rb")) == NULL) {
printf("can not open file\n");
exit(0);
}
for (i = 0; i < 10; i += 2) {
fseek(hzh, i * sizeof(struct Student), 0);
fread(&student[i], sizeof(struct Student), 1, hzh);
printf("| %d | %-5d | %-5s | %d | %-5s | %2.1f |\n", i + 1, student[i].number, student[i].name, student[i].age, student[i].sex, student[i].score);
}
fclose(hzh);
return 0;
}
This is the data that is read out, that is, displayed on the screen. This is not quite what I expected. I wonder why the data read out is a strange string of numbers. My feeling is that some data seems to be related to the address of a variable.
| 1 | 538981938 | lco 22 woman | 538996579 | 22 woman | 0.0 |
| 3 | 1634541600 | n 99.7
35 s | 775502112 | 7
35 s | 12686448208222805000000000000000.0 |
| 5 | 538980404 | vuk 21 woman | 538995573 | 21 woman | 0.0 |
| 7 | 1634541600 | n 72.3
21 j | 775042848 | 3
21 j | 48394959290400714000000000.0 |
| 9 | 538981429 | sei 20 man | 538995045 | 20 man | 0.0 |
And the result I want is:
| order_number | Student_ID | name | age | sex | score |
Here is the data I want to read:
26 lco 22 woman 76.1
59 ccb 20 man 99.7
35 syx 18 man 94.6
40 vuk 21 woman 84.4
57 ngp 21 man 72.3
21 jny 19 woman 90.6
54 sei 20 man 85.2
60 hgn 21 man 71.4
32 ohx 22 man 83.7
3 vpl 19 man 84.3
My initial guess is that there is some type of issue with the cleanliness of the data file from which you are reading your data. Reviewing the intent of the program, I built a test file containing ten student records utilizing the structure noted in the program. Following was the list of the test data.
Then, building your program and compiling it as is, following is the output the program produced utilizing the above test data.
Note that since the "for" loop is being incremented by a value of "2", every other record is being read from the file. With this sample data, every odd-numbered record is being read. And the data is printing as desired.
So the likely issue here is the integrity of the data file your program is reading and not so much the program. You might want to check with whoever provided the data that they indeed wrote the data to the file such that it matches the expected "Student" structure.
Check that out and see if it then meets the spirit of your project.