#### Archived

This topic is now archived and is closed to further replies.

# very simply, why wont this fread work

This topic is 6007 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

i have a text file called test.txt, and the only thing stored in this text file is the number "1". thats it.
  (stdio.h) (iostream.h) //yes these are included void main() { int num; FILE *in; in = fopen("c:/windows/desktop/test.txt", "r"); fread(num, sizeof(int), 1, in); fclose(in); cout << num << endl; } 
that doesn't work. it simply returns garbage like "1424384234". i also tried opening it in binary, using "rb". just gives me different garbage, like "132325827". i also tried freading like this: fread(num, 1, sizeof(int), in); but still doesn't work. why does this SIMPLE little thing NOT work?? Edited by - scanf on December 11, 2001 8:19:21 PM

##### Share on other sites

  fread(&num,sizeof(int),1,in);

Hope this helps...

---------------

I finally got it all together...
...and then forgot where I put it.

##### Share on other sites
You are simply passing the value of num in your code, but you should be giving fread access to CHANGE num - &num.

---------------

I finally got it all together...
...and then forgot where I put it.

##### Share on other sites
err, forgot to include that in the coding, yes i already do have the & before my variable num, and the problem still happens

##### Share on other sites
OK, revised version:

  fscanf(in,"%d",&num);

Hope THAT helps lol...

---------------

I finally got it all together...
...and then forgot where I put it.

##### Share on other sites
:O

can you give me an example of when its appropriate to use fread, and when its appropriate to use fscanf?

##### Share on other sites
Well, remember that when you write an int with the value of 1 using fwrite, it will NOT come out as 1 in the text file. It has been written in binary form, so it will take up two ''letters'' of space in the text file, both of which are very unlikely to be numbers. You could, though, use fread to recover that integer from the text file (the one u wrote with fwrite). But if you want to read an int which you have personally WRITTEN using notepad in a file, you would use fscanf. Also, you can use fprintf to write an int in a humanly-readable form to a text file.

Rule of the thumb: "Use fscanf when you used notepad to create the file, and fread when you used fwrite to create the file."

Hope this helps

---------------

I finally got it all together...
...and then forgot where I put it.

##### Share on other sites
use fscanf to read a string and convert it to a different type, e.g. string->integer or string->float

• 9
• 23
• 10
• 19