Read from stdin write to stdout in C

后端 未结 4 715
无人及你
无人及你 2021-02-03 15:55

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

#include 
#define BLOCK_SIZE 512
int main(int argc, const char *argv[])
{
    if         


        
4条回答
  •  借酒劲吻你
    2021-02-03 16:37

    Ignore my comment about fflush; that's not the issue.

    Swap the order of the block size and the element size in the fread call. You want to read up to BLOCK_SIZE elements of size 1 (sizeof (char) is 1 by definition); what you're doing is trying to read 1 element of size BLOCK_SIZE, so unless you type in at least BLOCK_SIZE characters, fread will return 0. IOW, your fread call needs to be

    size_t bytes = fread(buffer, 1, sizeof buffer, stdin);
    

    Make a similar change to the fwrite call.

提交回复
热议问题