如何对 fgets 使用 feof 和ferror(C 中的 minishell)[重复]

2024-01-03

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

我已经检查过 fgets 是否返回空指针(这表明缓冲区的内容是不确定的),但我想知道如何使用 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;
}

fgets(str, LINE_LEN, stdin);

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

这不是检查返回值的方式fgets。更重要的是,在你的代码中str永远不会NULL根据定义。你想要类似的东西:

if (!fgets(....)) }
    /* error handling. */
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何对 fgets 使用 feof 和ferror(C 中的 minishell)[重复] 的相关文章

随机推荐