为什么这个循环不会永远持续下去?初级C问题


#define MAXLINE 1000
char pattern[] = "ould";
main()
{
char line[MAXLINE];
int found = 0;
while (getline(line,MAXLINE) > 0)
if (strindex(line, pattern) >= 0 ) {
printf("%s", line);
found ++;
}
return found
}

为什么while循环会一直持续下去?getline(line,1000)将返回行长度,并"追加"行长度。(?)转换为MAXLINE,根据行长度…使数字大于1000。为什么会降到零以下呢?

我读到getline返回-1如果"不成功",那是什么时候?什么时候不读行?

这是在Kernighan的第69页。我一直在跳过这本书,我现在正在回溯,看看我错过了什么。

"描述你尝试了什么,你期望发生什么,以及实际结果如何。最少20个字符。">

K&R Second Edition第69页所示getline的版本定义为:

/* getline: get line into s, return length */
int getline(char s[], int lim)
{
int c, i;
i = 0;
while (--lim > 0 && (c=getchar()) != EOF && c != 'n')
s[i++] = c;
if (c == 'n')
s[i++] = c;
s[i] = '';
return i;
}

从这里我们可以看到,函数继续从stdin流中消费字符必须满足的条件之一是返回的字符不等于常数值EOF

(c=getchar()) != EOF

EOFend- file表示不再从流中读取数据。参见什么是C编程语言中的EOF ?查看更多详细信息。

如果getchargetline中第一次调用时返回EOF,则i将永远不会在0之后增加,并且该函数将返回0。

这个版本的getline不能返回-1

您所显示的情况

while (getline(line,MAXLINE) > 0)
当返回值小于等于

为零时,将导致循环停止。也就是说,当getline表示没有读取数据时。

我假设您使用的是书中定义的getlinestrindex:

/* getline: get line into s, return length */
int getline(char s[], int lim)
{
int c, i;
i = 0;
while (--lim > 0 && (c=getchar()) != EOF && c != 'n')
s[i++] = c;
if (c == 'n')
s[i++] = c;
s[i] = '';
return i;
}
/* strindex: return index of t in s, -1 if none */
int strindex(char s[], char t[])
{
int i, j, k;
for (i = 0; s[i] != ''; i++) {
for (j=i, k=0; t[k] != '' && s[j] == t[k]; j++, k++)
;
if (k > 0 && t[k] == '')
return i;
}
return -1;
}

可以看到,getline读取直到到达文件结束(EOF)。如果你在命令行上运行程序,你的程序正在等待这个信号,你可以通过按Control-d手动发送这个信号。

如果你将一个文件放入程序:

$ cat test.txt | ./your program

发送的文件结束值,位于文件末尾。

最新更新