how to write an integer to a file (the difference between fprintf and fwrite)

£可爱£侵袭症+ 提交于 2019-11-27 23:41:14

问题


I've been trying to write an integer to a file (open mode is w). fprintf wrote it correctly but fwrite wrote gibberish:

int length;
char * word = "word";

counter = strlen(word);
fwrite(&length, sizeof(int), 1, file);
fwrite(word, sizeof(char), length, file);

and the result in the file is:

word

but if I use fprintf instead, like this:

int length;
char * word = "word";

counter = strlen(firstWord);
fprintf(file, "%d", counter);
fwrite(word, sizeof(char), length, file);

I get this result in the file:

4word

can anyone tell what I did wrong? thanks!

update: I would eventually like to change the writing to binary (I will open the file in wb mode), will there be a difference in my implementation?


回答1:


fprintf writes a string. fwrite writes bytes. So in your first case, you're writing the bytes that represent an integer to the file; if its value is "4", the four bytes will be in the non-printable ASCII range, so you won't see them in a text editor. But if you look at the size of the file, it will probably be 8, not 4 bytes.




回答2:


Using printf() converts the integer into a series of characters, in this case "4". Using fwrite() causes the actual bytes comprising the integer value to be written, in this case, the 4 bytes for the characters 'w', 'o', 'r', and 'd'.



来源:https://stackoverflow.com/questions/6552907/how-to-write-an-integer-to-a-file-the-difference-between-fprintf-and-fwrite

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