How to use feof and ferror for fgets (minishell in C)

血红的双手。 提交于 2019-12-02 10:07:17

First of all, your test:

fgets(str, LINE_LEN, stdin);

[...]

if (str==NULL) {
    goto errorfgets;
}

is wrong. The str parameter is passed by value and cannot be modified by fgets(). Instead, you should be checking the value returned by fgets() (returns NULL on EOF or error).

Regarding your specific question: fgets() does not "return" feof or ferror. Both feof() and ferror() are actually functions (see the man pages). You would use this as follows:

if (!fgets(str, LINE_LEN, stdin)) {
    /* fgets returns NULL on EOF and error; let's see what happened */
    if (ferror(stdin)) {
        /* handle error */
    } else {
        /* handle EOF */
    }
}
fgets(str, LINE_LEN, stdin);

if (str==NULL) {
    goto errorfgets;
}

That's not how you check the return value of fgets. What's more, in your code str will never be NULL by definition. You want something like:

if (!fgets(....)) }
    /* error handling. */
}
Amit

You can use feof like this.

#open a file
fd = fopen (testFile,"r+b");

#read some data from file 
fread (&buff, 1, 1, fd);
..
..
..
#To check if you are at the end of file
if (feof (fd))
{
    printf("This is end of file");
}else{
    printf("File doesn't end. Do continue...");
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!