Read from stdin write to stdout in C

老子叫甜甜 提交于 2019-12-02 21:27:38
Peter Miehle

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

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

Your problem appears to be the return value of fread. I modified your code to print out the value bytes, and I get 0 every time. The man page for fread makes it clear that the return value of fread is NOT the number of characters. If EOF is encountered the return value could be zero (which it is in this case). This is because you are attempting to read in 1 thing that is size BLOCK_SIZE rather than BLOCK_SIZE things that are size 1.

Try calling fflush(stdout) after the fwrite()

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!