将标准输入写入文件

4
我试图将标准输入写入文件,但是出现读取零字节的问题。
以下是我的源代码:
#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

尽管我正在传输大量的内容,但似乎读取了零字节。


嗨 - 问题在于你使用了“read”的方式。请查看此链接以获取正确的用法和解决方案:在C中从stdin读取并写入stdout - paulsm4
下面的答案是正确的,但有一些风格(或其他较小)问题。首先,您可以将content声明为char数组。不需要使用malloc。其次,fread返回size_t而不是int,因此您的变量read具有不同的类型。您还应该重命名它以避免使用与全局函数相同的名称(read是一个全局函数,实际上是一个系统调用)。您的代码在未检查失败的情况下关闭了fp。即使无法打开“/tmp/mimail”,它也会读取stdin。 - James Youngman
1个回答

5

您将fread()的两个整数参数颠倒了。您告诉它只填充一次缓冲区,或者失败。相反,您希望告诉它读取单个字符,最多1024次。颠倒这两个整数参数,它就会按设计要求工作。


在源代码中添加一个长注释,使其长度超过BUF_SIZE是很有教育意义的。然后while循环将被执行一次。 - gcbenison
@gcbenison 使用test.c作为输入只是一个测试;它确实需要从stdin读取任何类型的数据。 - WhyNotHugo
@ernest-friedman-hill 谢谢,我的错,我没有太注意到那个。以后我会留意这种事情的 :) - WhyNotHugo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接