我试图将标准输入写入文件,但是出现读取零字节的问题。
以下是我的源代码:
我正在运行
以下是我的源代码:
#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
尽管我正在传输大量的内容,但似乎读取了零字节。
content
声明为char数组。不需要使用malloc
。其次,fread
返回size_t
而不是int
,因此您的变量read
具有不同的类型。您还应该重命名它以避免使用与全局函数相同的名称(read
是一个全局函数,实际上是一个系统调用)。您的代码在未检查失败的情况下关闭了fp
。即使无法打开“/tmp/mimail”,它也会读取stdin。 - James Youngman