C语言 C 读到文件末尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7921141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C Read until end of file
提问by Intelwalk
I currently have code that reads 4 lines and I want to be able to change that until EOF or my MAX const int value. I can not get the !EOF to work right and was wondering how would I change my code to accomplish this?
我目前有读取 4 行的代码,我希望能够更改它,直到 EOF 或我的 MAX const int 值。我无法让 !EOF 正常工作,想知道如何更改代码以完成此操作?
Thanks in advance
提前致谢
#include <stdio.h>
struct record{
char name[2];
int arrival_time;
int job_length;
int job_priority;
};
const int MAX = 40;
int main(void)
{
struct record jobs[MAX];
int i = 0;
int j;
FILE *f = fopen("data.dat","rb");
while (fscanf(f, "%s %d %d %d", &jobs[i].name, &jobs[i].arrival_time,
&jobs[i].job_length, &jobs[i].job_priority) == 4 && i < MAX)
i++;
for (j = 0; j < i; j++)
printf("%s %d %d %d\n", jobs[j].name, jobs[j].arrival_time,
jobs[j].job_length, jobs[j].job_priority);
fclose(f);
return(0);
}
回答by Martin Beckett
Something like
就像是
while (fscanf(f, " %s ", &etc) != EOF) {
}
Then use feof(f)to check if it was a fscanferror or actually EOF.
然后用于feof(f)检查它是fscanf错误还是实际上EOF。
回答by Piotr Praszmo
Your code seems to do what you want, except:
您的代码似乎按照您的意愿行事,除了:
char name[2];
Names will probably be longer than 1 character.
名称可能会超过 1 个字符。
FILE *f = fopen("data.dat","rb");
You seem to be reading text ("r") file, not binary ("rb").
您似乎正在阅读文本 ( "r") 文件,而不是二进制 ( "rb")文件。
&jobs[i].nameshould be jobs[i].name
&jobs[i].name应该 jobs[i].name
回答by caf
You need to change the order of the tests in your while()loop - you must test i < MAXbeforecalling fscanf(), or else you'll potentially call it one too many times (you should also be passing jobs[i].namewithout the &to fscanf):
您需要更改while()循环中测试的顺序- 您必须i < MAX在调用之前进行测试fscanf(),否则您可能会多次调用它(您也应该在jobs[i].name没有&to 的情况下传递fscanf):
while (i < MAX && fscanf(f, "%s %d %d %d", jobs[i].name, &jobs[i].arrival_time,
&jobs[i].job_length, &jobs[i].job_priority) == 4)
回答by Riccardo Scorretti
Personnaly, I would code like this:
Personnaly,我会这样编码:
for(i=0 ; i<MAX ; ++i) {
fscanf(f, "%s %d %d %d", &jobs[i].name, &jobs[i].arrival_time,
&jobs[i].job_length, &jobs[i].job_priority);
if(ferror(f) || feof(f)) break;
}
The key point is that, at the best of my knowledge, you cannot know that a file is come to end without trying to read it. That is the reason why I check feof() and ferror() after having read data. At the end of the loop, the variable i contains the number of read data
关键是,据我所知,如果不尝试阅读文件,您就无法知道文件即将结束。这就是我在读取数据后检查 feof() 和 ferror() 的原因。在循环结束时,变量 i 包含读取数据的数量

