使用 C popen(): read() 有效,但 fread() 无效

Using C popen(): read() work, but fread() doesn't

在 popen() 之后,fread() 总是 returns 0。将 read() 与 fileno(fp) 一起使用有效。怎么回事?

这是代码。

#include <errno.h>
#include <stdio.h>
#include <unistd.h>


int main(int argc, char *argv[]) {
    FILE *fp = popen("echo hello", "r");
    if (!fp) {
        perror("echo hello");
    } else {
        char buffer[128];
        for (;;) {
            int n;
            if (argc < 2) {
                n = fread(buffer, sizeof buffer, 1, fp);
            } else {
                n = read(fileno(fp), buffer, sizeof buffer);
            }
            printf("read %d bytes\n", n);
            if (n <= 0) break;
            fwrite(buffer, n, 1, stdout);
        }
        pclose(fp);
    }
}

如果没有命令行参数,代码使用 fread(),否则使用 read()。

输出:

$ ./test
read 0 bytes
$ ./test x
read 6 bytes
hello
read 0 bytes

您告诉 fread() 读取 1 个 100 字节长的项目。 fread() returns 已阅读的完整项目数。由于流中只有 6 个字节,在到达 EOF 之前它无法读取任何项目,因此它 returns 0.

交换 sizenitem 参数的顺序,然后它将每个字节视为一个单独的项目,return 它读取的字节数。

n = fread(buffer, 1, sizeof buffer, fp);