Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...