在 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
。
交换 size
和 nitem
参数的顺序,然后它将把每个字节视为一个单独的项目,并返回它读取的字节数。
n = fread(buffer, 1, sizeof buffer, fp);
关于c - 使用 C popen() : read() work, 但 fread() 没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68146566/