Reputation: 157
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;
}
Upvotes: 3
Views: 22239
Reputation: 53386
Size of int
is 4 bytes so your fread()
will try to read 12 bytes (4 * 3).
When you enter something like this on console
1 2 3
it is 6 chars = 3 numbers + 2 spaces + 1 \n
Hence you would have to press enter at lease 6 times so that it reads 6 more bytes.
Better to use scanf()
to get integers as
scanf("%d %d %d", &size[0], &size[1], &size[2]);
Upvotes: 0
Reputation: 249592
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.
Upvotes: 4