c - 在 C 中从 stdin 读取写入到 stdout

标签 c io stdout stdin stdio

我正在尝试编写一个猫克隆来练习 C,我有以下代码:

#include <stdio.h>
#define BLOCK_SIZE 512
int main(int argc, const char *argv[])
{
    if (argc == 1) { // copy stdin to stdout
        char buffer[BLOCK_SIZE];
        while(!feof(stdin)) {
            size_t bytes = fread(buffer, BLOCK_SIZE, sizeof(char),stdin);
            fwrite(buffer, bytes, sizeof(char),stdout);
        }
    }
    else printf("Not implemented.\n");
    return 0;
}

我试过了 echo "1..2..3.." | ./cat./cat < garbage.txt但我在终端上看不到任何输出。我在这里做错了什么?

编辑: 根据评论和答案,我最终这样做了:

void copy_stdin2stdout()
{
    char buffer[BLOCK_SIZE];
    for(;;) {
        size_t bytes = fread(buffer,  sizeof(char),BLOCK_SIZE,stdin);
        fwrite(buffer, sizeof(char), bytes, stdout);
        fflush(stdout);
        if (bytes < BLOCK_SIZE)
            if (feof(stdin))
                break;
    }

}

最佳答案

我可以引用我的回答:https://stackoverflow.com/a/296018/27800

fread(buffer, sizeof(char), block_size, stdin);

关于c - 在 C 中从 stdin 读取写入到 stdout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10129085/

相关文章:

java - 将 JVM 详细输出发送到 stderr 而不是 stdout

c - 从文件打印并存储在数组中。

haskell - 在 IO 之上构建 monad 转换器堆栈是否有正当理由?

c - 如何在 C 中为输入和输出文件运行命令行参数

c++ - 在 Windows 的 C++ 控制台应用程序中重新定义 'pause' 行为

windows - 将 stderr 重定向到文件,但保持屏幕上的所有输出完好无损 (as_is)。 [Windows XP - BAT 文件]

ruby - 如何在终端中使用 Sequel gem 显示一般查询日志

C:使用 read 系统调用从 stdin 读取 double

c - 为什么这段代码给我一个段错误?

c - 删除链表最后一项