如何对fget使用虚假和恐怖(C语言中的minishell) [英] How to use feof and ferror for fgets (minishell in C)
问题描述
我已经编写了这个minishell,但是不确定我是否对错误进行了正确的控制.我知道fgets可以返回虚假信息和错误信息( http://www.manpagez.com/man/3 /fgets/) 但我不知道如何使用它们.
I've written this minishell but I'm not sure I'm making a correct control of the errors. I know fgets can return feof and ferror (http://www.manpagez.com/man/3/fgets/) but I don't know how to use them.
我已经检查了fgets是否返回一个空指针(这表明缓冲区的内容是不确定的),但是我想知道如何使用feof和ferror.
I've checked if fgets returns a null pointer (which indicates the content of the buffer is inditerminate) but i would like to know how to use feof and 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;
}
是错误的. str
参数按值传递,并且不能由fgets()
修改.相反,您应该检查fgets()
返回的值(在EOF或错误时返回NULL
).
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).
关于您的特定问题:fgets()
不会返回" feof
或ferror
. feof()
和ferror()
实际上都是功能(请参见手册页).您将按以下方式使用它:
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 */
}
}
这篇关于如何对fget使用虚假和恐怖(C语言中的minishell)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!