我找到了一个接受标准输入的程序
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <PATTERN>\n", argv[0]);
return 2;
}
/* we're not going to worry about long lines */
char buf[4096]; // 4kibi
while (!feof(stdin) && !ferror(stdin)) { // when given a file through input redirection, file becomes stdin
if (!fgets(buf, sizeof(buf), stdin)) { // puts reads sizeof(buf) characters from stdin and puts it into buf; fgets() stops reading when the newline is read
break;
}
if (rgrep_matches(buf, argv[1])) {
fputs(buf, stdout); // writes the string into stdout
fflush(stdout);
}
}
if (ferror(stdin)) {
perror(argv[0]); // interprets error
return 1;
}
return 0;
}
为什么buf设置为4096个元素?是因为每行最大字符数只能是4096吗?
最佳答案
答案在您粘贴的代码中:
/* we're not going to worry about long lines */
char buf[4096]; // 4kibi
可能会出现超过 4096 个字符的行,但作者认为它们不值得关心。
另请注意 fgets
的定义:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (
\0
) is stored after the last character in the buffer.
因此,如果一行的长度超过 4095 个字符(因为第 4096 个字符保留给空字节),它将被拆分到 while
循环的多次迭代中。
关于c - 为什么使用 4096 个元素作为 char 数组缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22060177/