为什么将4096个元素用于char数组缓冲区? [英] Why use 4096 elements for a char array buffer?
问题描述
我发现一个程序接受标准输入
I found a program that takes in standard input
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?
Why is the buf set to 4096 elements? Is it because the maximum number of characters on each line can only be 4096?
推荐答案
答案是在您粘贴的代码中:
The answer is in the code you pasted:
/* we're not going to worry about long lines */
char buf[4096]; // 4kibi
行数可能超过4096个字符,但作者并不认为它们值得关注关于。
Lines longer than 4096 characters can occur, but the author didn't deem them worth caring about.
还要注意 fgets
:
fgets()从流中读取最多小于大小的字符,并将其存储到s指向的缓冲区中。在EOF或换行符之后停止读取。如果读取换行符,则将其存储到缓冲区中。终止的空字节(
\0
)存储在缓冲区的最后一个字符之后。
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
循环的多次迭代。
So if there is a line longer than 4095 characters (since the 4096'th is reserved for the null byte), it will be split across multiple iterations of the while
loop.
这篇关于为什么将4096个元素用于char数组缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!