Reputation: 1
I have question about fprintf and fwrite. How many bytes are written when this code runs (assuming fp has been correctly set up).
int i = 10000;
fprintf(fp,"%d",i);
fwrite(fp,sizeof(int),1,&i);
When I checked then 5 bytes and 9 bytes respectively. Maybe I am wrong. I thought it is 4 bytes since int. Can someone explain please??? Thanks.
Upvotes: 0
Views: 2822
Reputation: 53006
fprintf
writes the string 10000
(5 bytes) to the file, while fwrite
writes binary representation of 10000
(sizeof(int)
bytes) to the file.
Upvotes: 2
Reputation: 9429
fprintf(fp,"%d",i);
writes 5 bytes. it writes 10000 as string, 5 chars
Upvotes: 1
Reputation: 2638
How are you checking the number of bytes written? sizeof(int) depends on platform.
Given below is the function signature for fwrite.
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
fwrite writes an array of count elements, each one with a size of size bytes, from the block of memory pointed by ptr to stream. The return value gives the actual number of bytes written. Mostly it is going to be size * count.
Similarly fprintf returns the number of characters written/printed.
Upvotes: 1