首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么使用4096个元素作为char数组缓冲区?

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

Stack Overflow用户
提问于 2014-02-27 05:55:08
回答 5查看 5.2K关注 0票数 3

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

代码语言:javascript
运行
复制
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个吗?

EN

Stack Overflow用户

发布于 2014-02-27 06:06:25

行中没有最大字符这样的东西。4096是假定正常情况下的无一行数将超过4096字节。

更像是在为最坏的情况做准备。

假设数组的大小小于大小(行),然后将操作分解为多个步骤,直到遇到eof。

票数 1
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22060177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档