c - how to write an integer to a file (the difference between fprintf and fwrite) -
i've been trying write integer file (open mode w). fprintf wrote correctly fwrite wrote gibberish:
int length; char * word = "word"; counter = strlen(word); fwrite(&length, sizeof(int), 1, file); fwrite(word, sizeof(char), length, file);
and result in file is:
word
but if use fprintf instead, this:
int length; char * word = "word"; counter = strlen(firstword); fprintf(file, "%d", counter); fwrite(word, sizeof(char), length, file);
i result in file:
4word
can tell did wrong? thanks!
update: change writing binary (i open file in wb mode), there difference in implementation?
fprintf
writes string. fwrite
writes bytes. in first case, you're writing bytes represent integer file; if value "4", 4 bytes in non-printable ascii range, won't see them in text editor. if @ size of file, 8, not 4 bytes.
Comments
Post a Comment