Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

printf

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?

like image 852
Shai Balassiano Avatar asked Jul 01 '11 20:07

Shai Balassiano


People also ask

What is the difference between fprintf and fwrite?

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.

Is fwrite faster than fprintf?

But what about fprintf() vs fwrite()? For all intents and purposes, fprintf() is pretty much the same speed as fwrite(). BUT fprintf is DEFINITELY much faster than ofstream!

What is the difference between printf () and fprintf () in the C language?

The fprintf function formats and writes output to stream. It converts each entry in the argument list, if any, and writes to the stream according to the corresponding format specification in format. The printf function formats and writes output to the standard output stream, stdout .

Does fwrite write at the end of file?

The fwrite() writes to an open file. The function will stop at the end of the file (EOF) or when it reaches the specified length, whichever comes first.


2 Answers

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.

like image 102
vanza Avatar answered Sep 20 '22 07:09

vanza


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'.

like image 25
David R Tribble Avatar answered Sep 21 '22 07:09

David R Tribble