c - 使用 C popen() : read() work, 但 fread() 没有

标签 c popen fread

在 popen() 之后,fread() 始终返回 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() 返回已读取的完整项目数。由于流中只有 6 个字节,因此在到达 EOF 之前无法读取任何项目,因此它返回 0

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

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

关于c - 使用 C popen() : read() work, 但 fread() 没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68146566/

相关文章:

c - 在 C99 标准中,将 unsigned int 转换为 unsigned char 的行为是什么?

c - 从 USB 设备读取并写入物理地址

c - 搜索二叉搜索树,使用计数器进行迭代

c - 如何禁用 fread() 中的缓冲?

c - 我想将 stdin 解释为二进制文件。为什么 freopen 在 Windows 上失败?

c - 使用 AVL 树进行哈希处理

将 Ruby 转换为 C 语言,有人愿意看一下吗?

python - web.py + 子进程 = 挂起

python subprocess.Popen stdin.write

c++ - 我可以用c++中的istream读取二进制数据吗?