-3

I know that fread is not meant to be used with non-binary files. However, I was wondering: If I provide the function with the correct size of the input, why shouldn't it return the correct values, but instead it returns garbage?

FILE *fp;
int val = 0;

if(fp = fopen("test.txt", "r")){
    fread(&val, sizeof(int), 1, fp);
    printf("val read %d \n", val);

    fclose(fp);

}

if(fp = fopen("test.txt", "r")){
    fscanf(fp, "%d", &val);
    printf("val read %d \n", val);

    fclose(fp);

}

As an example, if I read a file with inside only 1234567, the output is

val read 875770417

val read 1234567 
barry91
  • 19
  • 4
  • 1
    What's the meaning of garbage? Which is the content of the file? Which is the output? – Lopan Feb 12 '17 at 15:11
  • What file are you reading and what kind of garbage you're getting? Please include the most relevant parts _in the question_ (not in comments). – ForceBru Feb 12 '17 at 15:12
  • Sorry, I made the wrong question. I meant fread and not fscanf. I added an example too. – barry91 Feb 12 '17 at 15:25

2 Answers2

2

You are using fscanf with the -d specifier which according to the specification extracts - Any number of decimal digits (0-9), optionally preceded by a sign (+ or -).

The problem is that digits are not stored as strings in binary file but as bytes. To read the data in bytes use fread. Please see here: Using fscanf in binary mode

Community
  • 1
  • 1
Dave S
  • 973
  • 9
  • 17
  • Thanks for you reply Dave. I believe I made an error while writing the question, the real one was related to the fread function. I do not understand why it should not work with non-binary files – barry91 Feb 12 '17 at 15:31
  • @barry91 - NP. A similar question was asked in the past and should answer your question - http://stackoverflow.com/questions/11326852/c-fread-binary-number-and-convert-it-to-ascii-code – Dave S Feb 12 '17 at 16:14
1

If it says 1234567 in your file as text you can read it with fread as well

but fread(&val, sizeof(int), 1, fp); is not correct, it presumes that the integer was written with binary representation i.e. as an int, not as text, so instead you need to read it as text:

char buf[8];
fread(buf,1, sizeof(buf)-1, fp);
buf[sizeof(buf)-1] = '\0';

now you have the string 1234567 in buf

puts(buf);
AndersK
  • 35,813
  • 6
  • 60
  • 86