c - 将标准输入写入文件

标签 c stream pipe 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

似乎读取了零字节,即使我正在传输很多东西。

最佳答案

您已将 fread() 的两个整数参数颠倒过来。您告诉它填充缓冲区一次,否则失败。相反,您想告诉它读取单个字符,最多 1024 次。反转两个整数参数,它将按设计工作。

关于c - 将标准输入写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10769205/

相关文章:

c - 无论如何,我可以在没有预处理器指令的情况下有条件地初始化成员吗?

c - 未创建多个队列 - C

php - 流输出到文本文件php centos

c++ - C++ 新手,想知道 getline() 和 cin 在我的代码中做了什么

perl - 如何通过管道使用 Parallel::ForkManager?

bash - 通过管道从 subshel​​l 获取退出代码

c - 格雷码递增函数

Java Play FrameWork 2.3 使用 jackson 返回流式 Json

c - 来自curl_easy_perform的管道数据

c - 在屏幕和文本文件上打印