我正在尝试将stdin写入文件,但出于某种原因,我注意读取零字节。
这是我的来源:
#include <stdio.h>
#include <stdlib.h>
#define BUF_SIZE 1024
int main(int argc, char* argv[]) {
if (feof(stdin))
printf("stdin reached eof\n");
void *content = malloc(BUF_SIZE);
FILE *fp = fopen("/tmp/mimail", "w");
if (fp == 0)
printf("...something went wrong opening file...\n");
printf("About to write\n");
int read;
while ((read = fread(content, BUF_SIZE, 1, stdin))) {
printf("Read %d bytes", read);
fwrite(content, read, 1, fp);
printf("Writing %d\n", read);
}
if (ferror(stdin))
printf("There was an error reading from stdin");
printf("Done writing\n");
fclose(fp);
return 0;
}
我正在运行cat test.c | ./test
,输出只是
About to write
Done writing
看起来零字节被读取,即使我管道很多东西。
答案 0 :(得分:4)
你有fread()
反转的两个整数参数。你告诉它填充缓冲区一次,或者失败。相反,您想告诉它读取单个字符,最多1024次。反转两个整数参数,它将按设计工作。