[英]Newline, EOF and feof() aren't acknowledged
I have a function that does the following: 我有一个功能,可以执行以下操作:
ssize_t headache(char **lineptr, size_t *n, FILE * stream)
{
if(lineptr != NULL)
{
free(*lineptr);
}
size_t len = 0,
last = 0;
char * buf = NULL;
int c;
do
{
last = len;
++len;
buf = realloc(buf,len);
c = fgetc(stream);
buf[last] = (char)c;
printf("%i\t%x\t%c\n", last, buf[last], buf[last]);
}
while(!feof(stream) || c != '\n');
*n = strlen(buf);
*lineptr = buf;
return len;
}
headache is always called headache(&lineptr,&n,stream) where 头痛总是叫头痛(&lineptr,&n,stream)在哪里
char * lineptr = NULL;
size_t n = 0;
FILE * stream;
The do{}while(); do {} while(); loop will never acknowledge a newline or EOF, meaning that it will continue in infinity. 循环将永远不会确认换行符或EOF,这意味着它将继续在无穷大。 I don't understand why is it ignoring EOF and '\\n'. 我不明白为什么它忽略了EOF和'\\ n'。 Can someone please tell me what did I do wrong? 有人可以告诉我,我做错了什么?
while(!feof(stream) || c != '\n');
will loop again unless both conditions evaluate to false. 将再次循环,除非两个条件评估为false。 You want to exit the loop when you either receive EOF
or \\n
so should use &&
instead 你想要在接收EOF
或\\n
时退出循环,所以应该使用&&
代替
while(!feof(stream) && c != '\n');
Your issue is with 你的问题是
while(!feof(stream) || c != '\\n')
this is because using || 这是因为使用|| (or) you have to make both conditions false for it to stop execution. (或)你必须使两个条件都为假,以便停止执行。 There are inputs that would make your while loop never end. 有些输入会使你的while循环永远不会结束。 this is a test input
vs. this is a test input\\n
. this is a test input
而this is a test input\\n
。
If you are running this as stdin as your file*
compare what happens when you run it with you typing a message and pressing enter and you typing a message and pressing control-d (which is EOF in a terminal) 如果您将此作为stdin运行作为您的file*
比较当您运行它时键入消息并按Enter键然后键入消息并按control-d(在终端中为EOF)
As stated by simonc you need the && operator which only requires one of the conditions to be false for it to stop. 正如simonc所说,你需要&&运算符,它只需要一个条件为false就可以停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.