Test
为了找到的行为getline()
当遇到 EOF 时,我编写了以下测试:
int main (int argc, char *argv[]) {
size_t max = 100;
char *buf = malloc(sizeof(char) * 100);
size_t len = getline(&buf, &max, stdin);
printf("length %zu: %s", len, buf);
}
输入1是:
abcCtrl-DEnter
Result:
length 4: abc //notice that '\n' is also taken into consideration and printed
Input2:
abcEnter
完全相同的输出:
length 4: abc
看来EOF
被排除在外getline()
源代码
所以我找到了的源代码getline() http://sourcecodebrowser.com/pecomato/0.0.15/gnu-getline_8c.html以下是它的相关片段(为了简洁起见,我省略了一些注释和不相关的代码):
while ((c = getc (stream)) != EOF)
{
/* Push the result in the line. */
(*lineptr)[indx++] = c;
/* Bail out. */
if (c == delim) //delim here is '\n'
break;
}
/* Make room for the null character. */
if (indx >= *n)
{
*lineptr = realloc (*lineptr, *n + line_size);
if (*lineptr == NULL)
return -1;
*n += line_size;
}
/* Null terminate the buffer. */
(*lineptr)[indx++] = 0;
return (c == EOF && (indx - 1) == 0) ? -1 : indx - 1;
Question
所以我的问题是:
- 为什么这里的长度是4(据我所知应该是5)(因为wiki http://en.wikipedia.org/wiki/End-of-file说,如果它不在行的开头,它就不会是 EOF)
类似的问题:伴随其他值时的 EOF 行为 https://stackoverflow.com/questions/17162167/eof-behavior-when-accompanied-by-other-values但请注意该问题中的 getline() 与 GNU-getline 不同
我使用GCC:(Ubuntu 4.8.2-19ubuntu1)4.8.2