lychee
lychee

Reputation: 1861

fread() function gives garbage

I can't understand why this little C code doesn't work

#include <stdio.h>

main(int argc,char **argv){
     FILE *fp,
     int i;
     size_t elem_read;
     int buffer[100];
     fp=fopen(argv[1],"r");
     elem_read=fread(buffer,sizeof(int),100,fp);
     for(i=0;i<elem_read;i++)
            fprintf(stderr,"%d\t",buffer[i]);
     fclose(fp);
}

To shorten the code I haven't done any error checking but it should work...I have tried it with both txt and bin file to read numbers and print them out. I think I understand why this doesn't work with txt files, but I dont understand why it doesn't with .bin files? I have a file that contains 4 ints: 10 10 10 10, but when I try to run it with ./a.out file.bin I get some randomg numbers(garbage output), Where's the problem?

Upvotes: 1

Views: 790

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

The reason it does not work with .bin file is that if you can see 10 10 10 10 in your text editor, you've got a text file with a .bin extension. The values that you read are not "garbage", though: they are bytes that represent the text in the encoding of your file, re-interpreted as integers.

In order to read the numbers back as ints, write a program that writes binary numbers to a file, like this

FILE *fp = fopen("test", "wb");
int[] data = {10, 10, 10, 10};
fwrite(data, sizeof(int), sizeof(data)/sizeof(int), fp);
fclose(fp);

and then use your program to read them.

Upvotes: 6

Related Questions