从标准输入写入读取C到stdout [英] Read from stdin write to stdout in C

查看:1703
本文介绍了从标准输入写入读取C到stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个猫克隆锻炼C,我有这样的code:

 的#include<&stdio.h中GT;
#定义BLOCK_SIZE 512
INT主(INT ARGC,为const char * argv的[])
{
    如果(ARGC == 1){//拷贝标准输入到标准输出
        字符缓冲区[BLOCK_SIZE]
        而(!的feof(标准输入)){
            为size_t字节= FREAD(缓冲,BLOCK_SIZE,sizeof的(炭),标准输入);
            FWRITE(缓冲,字节的sizeof(炭),标准输出);
        }
    }
    其他的printf(未实现\\ n);
    返回0;
}

我试过回声1..2..3。| ./cat ./猫< garbage.txt ,但我没有看到终端的任何输出。我做错了的是什么?

编辑:
根据意见和答案,我结束了这样:

 无效copy_stdin2stdout()
{
    字符缓冲区[BLOCK_SIZE]
    为(;;){
        为size_t字节= FREAD(缓冲区的sizeof(炭),BLOCK_SIZE,标准输入);
        FWRITE(缓冲区的sizeof(炭),字节,标准输出);
        fflush(标准输出);
        如果(字节< BLOCK_SIZE)
            如果(的feof(标准输入))
                打破;
    }}


解决方案

我可以通过我举一个答案:的http://计算器.COM / A /二万七千八百分之二十九万六千零一十八

  FREAD(缓冲区的sizeof(炭),BLOCK_SIZE,标准输入);

I am trying to write a cat clone to exercise C, I have this code:

#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;
}

I tried echo "1..2..3.." | ./cat and ./cat < garbage.txt but I don't see any output on terminal. What I am doing wrong here?

Edit: According to comments and answers, I ended up doing this:

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;
    }

}

解决方案

i can quote an answer by me: http://stackoverflow.com/a/296018/27800

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

这篇关于从标准输入写入读取C到stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆