C语言 如何读取到文件 C 的末尾,fscanf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43098701/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:38:25  来源:igfitidea点击:

How to read until end of file C, fscanf

cfileeof

提问by R. Naired

What i read from a file: a P1/ s/ e/ t etc. / for different line. After specific letters(like 'a') come some data i have to collect so i don't want to use fgets. It doesn't end running. Could you help me, please?

我从文件中读取的内容:不同行的 P1/ s/ e/ t 等/。在特定字母(如“a”)之后,我必须收集一些数据,所以我不想使用 fgets。它并没有结束运行。请问你能帮帮我吗?

char com[21];
fscanf(src,"%s",com);
while(com!=EOF)
{
    if(com[0]=='a')
        fprintf(dest,"%s 1",com);
     if(com[0]=='s')
        fprintf(dest,"%s 2",com);
    fscanf(src,"%s",com);
}

回答by usr

Simple way is to test if fscanf()succeeded as the loop condition and you don't need a fscanf()before the loop:

简单的方法是测试是否fscanf()成功作为循环条件,并且fscanf()在循环之前不需要 a :

char com[21];

while(fscanf(src,"%20s",com) == 1)
{
    if(com[0]=='a')
        fprintf(dest,"%s 1",com);
     if(com[0]=='s')
        fprintf(dest,"%s 2",com);
}

fscanf()returns the number of items successfully scanned. So, you don't need to check if it' returned EOF.

fscanf()返回成功扫描的项目数。因此,您无需检查它是否已返回EOF

Note that I changed the format string to avoid buffer overflow. I suggest you use fgets()instead of fscanf()(and remember to take care of newline chars if it matters).

请注意,我更改了格式字符串以避免缓冲区溢出。我建议您使用fgets()而不是fscanf()(如果重要,请记住处理换行符)。

回答by Jay

Please note that fscanfreturns an integerwhich can indicate EOFwhen the End of File is reached. Please refer to the man pages for more detail.

请注意,fscanf返回一个integer可以指示EOF何时到达文件结尾。有关更多详细信息,请参阅手册页。

Your code will have to modified like below:

您的代码必须修改如下:

char com[21];
int ret;
ret = fscanf(src,"%s",com);
while(ret!=EOF)
{
    if(com[0]=='a')
        fprintf(dest,"%s 1",com);
     if(com[0]=='s')
        fprintf(dest,"%s 2",com);
    ret = fscanf(src,"%s",com);
}