[英]How to use feof and ferror for fgets (minishell in C)
我已经写了这个minishell,但是我不确定我是否正确控制了错误。 我知道fget可以返回虚假信息和错误( 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
从定义str
永远不会为NULL
。 您想要类似的东西:
if (!fgets(....)) }
/* error handling. */
}
您可以像这样使用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...");
}
首先,您的测试:
fgets(str, LINE_LEN, stdin);
[...]
if (str==NULL) {
goto errorfgets;
}
是错的。 str
参数按值传递,不能由fgets()
修改。 相反,您应该检查fgets()
返回的NULL
在EOF或错误时返回NULL
)。
关于您的特定问题: fgets()
不会“返回” feof
或ferror
。 feof()
和ferror()
都实际上是函数(请参见手册页 )。 您将按以下方式使用它:
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 */
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.