c - 为什么使用 4096 个元素作为 char 数组缓冲区?

标签 c buffer

我找到了一个接受标准输入的程序

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/

相关文章:

list - 为什么Buffer和List对象相等(即使它们来自不同的类)?

python - 将 Python 中的字节从 Numpy 数组复制到字符串或字节数组中

c - 循环缓冲区的结束指针问题

c - 从字符串中删除子字符串

c - 我的编译器不支持透明 union 。我该如何解决这个问题?

c - 子表达式的求值顺序

c - 如何正确读取标准输入的任意长度输入?

c - 当文件大小增加时,如何进行复用I/O来读取多个文件?

c 函数指针

python - 在编写时更新 Tkinter 文本小部件,而不是在类(class)结束后更新