如何在fgets中使用feof和ferror(C中的minishell)

时间:2014-02-12 09:41:31

标签: c fgets feof ferror

我写过这个minishell,但我不确定我是否正确控制错误。我知道fgets可以回归feof和ferror(http://www.manpagez.com/man/3/fgets/) 但我不知道如何使用它们。

我已经检查过fgets是否返回一个空指针(表示缓冲区的内容是inditerminate),但我想知道如何使用feof和ferror。

    #include <stdio.h>
    #include <stdlib.h> 
    #include <string.h> 
    #include <stdbool.h>    
    #define LINE_LEN  50
    #define MAX_PARTS  50 
    int main ()
    {
    char* token;
    char str[LINE_LEN];
    char* arr[MAX_PARTS];
    int i,j;
    bool go_on = true;

    while (go_on == true){
        printf("Write a line:('quit' to end) \n $:");
        fgets(str, LINE_LEN, stdin);

        if (str==NULL) {
            goto errorfgets;
        } else {
            size_t l=strlen(str);
            if(l && str[l-1]=='\n')
                str[l-1]=0;

            i=0;
            /* split string into words*/
            token = strtok(str, " \t\r\n");
            while( token != NULL ) 
            {
                arr[i] = token;
                i++;
                token = strtok(NULL," \t\r\n");
            }

            fflush(stdin);

            /* check if the first word is quit*/
            if (strcmp(arr[0],"quit")==0)
            {
                printf("Goodbye\n");
                go_on = false;
            } else {

                for (j=0; j < i; j++){
                printf("'%s'\n", arr[j]);       
                }   
            }
        }
    }

    return 0;
    errorfgets:
        printf("fgets didn't work correctly");
        return -1;
}

3 个答案:

答案 0 :(得分:3)

fgets(str, LINE_LEN, stdin);

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

这不是你检查fgets的返回值的方法。而且,根据定义,代码str永远不会是NULL。你想要这样的东西:

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

答案 1 :(得分:2)

你可以使用这样的feof。

#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...");
}

答案 2 :(得分:2)

首先,你的测试:

fgets(str, LINE_LEN, stdin);

[...]

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

错了。 str参数按值传递,fgets()无法修改。相反,您应该检查fgets()返回的值(在EOF上返回NULL或错误)。

关于您的具体问题:fgets()不会“返回”feofferrorfeof()ferror()实际上都是函数(请参阅man pages)。您可以按如下方式使用它:

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 */
    }
}