将标准输入写入文件

问题描述:

我正在尝试将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

嗨 - 问题是你使用“阅读”的方式。看看这个链接的正确用法 - 和一个解决方案:[从标准输入读取到标准输出写入C](http://stackoverflow.com/questions/10129085/read-from-stdin-write-to-stdout-in-c ) – paulsm4

+0

下面的答案是正确的,但有一些风格(或者其他方面稍微有点小问题)。一个是你可以将'content'声明为char数组。不需要'malloc'。其次,'fread'返回'size_t',而不是'int',所以你的变量'read'具有不同的类型。您还应该重命名它以避免使用与全局函数相同的名称('read'是一个全局函数,实际上是一个系统调用)。你的代码在不检查失败的情况下关闭'fp'。即使无法打开'/ tmp/mimail',它也会读取stdin。 –

你有两个整数参数fread()逆转。你告诉它填充一次缓冲区,或者失败。相反,你想告诉它读取单个字符,最多1024次。反转这两个整数参数,它将按设计工作。

+0

向源添加长评论使其长于BUF_SIZE很有意义。然后'while'循环进入一次。 – gcbenison

+0

@gcbenison使用test.c作为输入只是一个测试;它确实需要从stdin读取任何类型的数据。 – WhyNotHugo

+0

@ ernest-friedman-hill谢谢,我的坏,我没有注意到这一点。我将继续关注这类事情:) – WhyNotHugo