Search code examples
cstdoutfwrite

fwrite doesnt print anything to stdout


When I run this small code and enter 3 integers on the console, it doesn't print out as it should due to the fwrite statement. It prints only after I keep hitting enter for some time. Help? P.S: Learning faster ways than scanf and printf.

#include<stdio.h>
int main(){
    int size[3];
    fread(&size,sizeof(int),3,stdin);
    fwrite(&size,sizeof(int),3,stdout);
    fflush(stdout);
    return 0;
}

Solution

  • This is because fread reads binary data, not formatted text, so when you tell it to read 3 "ints" it will read 3*4=12 bytes of raw data from stdin. If you type "1" "2" "3" that's only three bytes of text, plus three newlines. Once you type twelve bytes it will probably get past that part, but then your program is probably broken, assuming you wanted to read and write actual text.

    You mean you're "learning faster ways than scanf and printf." Well, this is not a faster way, it's just a broken way. If you're having a performance issue in some code using scanf & printf, please ask a separate question and we can help with that.