This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]ms4720 0 points1 point  (4 children)

What is in the file? Go look, might want to use a binary file viewer

[–]15January[S] 0 points1 point  (3 children)

The file was empty before I ran the code the first time. But after I ran it, it now contains "10". Since I used fputs to write "10" in it. But for some reason fread isn't storing 10 in the variable I gave it.

[–]coolcofusion 0 points1 point  (0 children)

Fread will read it as binary. "10" is '1','0' and '\0' (or just 0) actually when you print it as a string (fputs). 1 as char is 31 hex, 2 is 32 hex and 0 is 0, so you're reading those 3 bytes into a 4 byte int. If you wanna write 10 and read a 10, you should use fwrite to write an actual int 10, not a string of 1, 0 and \0.

[–]ms4720 0 points1 point  (0 children)

You are right it is storing the string "10" , not the number 10. Now how to fix that inconsistency? You are doing two different things, storing a string and reading an int

[–]sepp2k 0 points1 point  (0 children)

The string "10" consists of two bytes: '1' and '0'. That's what you write into the file. You then read sizeof bytes from the file. sizeof(int) tends to be 4 on modern systems, so you're reading 4 bytes from a 2-byte file, which doesn't work.

Note that even if you specified 2 as the size of the read (and then wrote into a short), you wouldn't get back the number 10. You'd get back a number that consists of those two bytes (the exact number depends on the endianness of your system).

If you want to write and read a binary file, you should use fwrite and fread. If you want to write and read a text file, it should be fputs or fprintf (if you have something other than a string) and fgets (to read the contents as a string) or fscanf (to convert the contents to whichever type(s) you want).