[英]My loop isn't working(using feof)
FILE *test;
student st;
int i = 0;
test = fopen("example.bin", "rb");
while (feof(test))
{
fread(&st, sizeof(st),1,test);
Class[i] = st;
i++;
}
fclose(test);
So my question is how to read it, put the data in my structure and stop the loop? 所以我的问题是如何读取它,将数据放入我的结构中并停止循环?
See why is while(feof) always wrong . 看看为什么while(feof)总是错误的 。
Instead, you should loop until you fail to read a student: 相反,您应该循环播放直到看不到学生为止:
while (1 == fread(&st, sizeof st, 1, test))
{
Class[i++] = st;
}
Also it would be good to make sure you don't overflow the buffer of Class
, so put in a check for i
too, eg: 另外,最好不要使Class
的缓冲区溢出,所以也要检查一下i
,例如:
for (i = 0; i < MAX_CLASS && 1 == fread(&st, sizeof st, 1, test); ++i)
{
Class[i] = st;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.