以下代码的目的是从磁盘文件中读取数据:
#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;
}
这是读出的数据,也就是显示在屏幕上的数据。这不是我所期望的。不知为何读出的数据是一串奇怪的数字。我的感觉是有些数据好像跟某个变量的地址有关
| 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 |
而我想要的结果是:
| order_number | Student_ID | name | age | sex | score |
我最初的猜测是您从中读取数据的数据文件的清洁度存在某种类型的问题。回顾程序的意图,我利用程序中提到的结构构建了一个包含十个学生记录的测试文件。以下是测试数据列表。
| 1 | 1 | adf | 20 | woman | 68.0 |
| 2 | 2 | beg | 22 | woman | 71.0 |
| 3 | 3 | cfh | 24 | woman | 74.0 |
| 4 | 4 | dgi | 26 | woman | 77.0 |
| 5 | 5 | ehj | 28 | woman | 80.0 |
| 6 | 6 | fik | 30 | man | 83.0 |
| 7 | 7 | gjl | 32 | man | 86.0 |
| 8 | 8 | hkm | 34 | man | 89.0 |
| 9 | 9 | iln | 36 | man | 92.0 |
| 10 | 10 | jmo | 38 | man | 95.0 |
然后,构建您的程序并按原样编译,以下是利用上述测试数据生成的程序的输出。
@Vera:~/C_Programs/Console/StudentList/bin/Release$ ./StudentList
| 1 | 1 | adf | 20 | woman | 68.0 |
| 3 | 3 | cfh | 24 | woman | 74.0 |
| 5 | 5 | ehj | 28 | woman | 80.0 |
| 7 | 7 | gjl | 32 | man | 86.0 |
| 9 | 9 | iln | 36 | man | 92.0 |
请注意,由于“for”循环递增了“2”的值,因此每隔一条记录都会从文件中读取。使用此样本数据,将读取每条奇数记录。并且数据正在按需要打印。
所以这里可能的问题是您的程序正在读取的数据文件的完整性,而不是程序本身。您可能想与提供数据的人核实他们确实将数据写入文件,使其与预期的“学生”结构相匹配。
检查一下,看看它是否符合您项目的精神。