我找到了一个接收标准输入的程序
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个吗?
发布于 2014-02-27 06:06:25
行中没有最大字符这样的东西。4096是假定正常情况下的无一行数将超过4096字节。
更像是在为最坏的情况做准备。
假设数组的大小小于大小(行),然后将操作分解为多个步骤,直到遇到eof。
https://stackoverflow.com/questions/22060177
复制相似问题