user3386167
user3386167

Reputation: 65

Reading binary file results in garbage value

#include<stdio.h>
#include<stdlib.h>
int main()
{
 int *buffer;
 int i;
 FILE *fp;
 buffer=(int *)malloc(256);
fp=fopen("BACKING_STORE.bin", "r");  //BACKING_STORE.bin is a binary file of size 65K bytes
fseek(fp, 0, SEEK_SET);              //and I am trying to read 256 bytes at a time and storing 
fread(buffer, 256, 1, fp);           //it into buffer of size 256 bytes and printing that buffer
 printf("Data=%d\n", buffer);        //on screen.

 fclose(fp);
}

When I run this program, I get garbage values in result. I know this because in the fseek() function I change offset. Like first when I take offset as 0 it gives me some value let's say 12342539 then I change offset to 256 it gives me output as 14562342 and again when I set offset to 0 it gives me a different output 15623478. So this is how it is showing output which is garbage.

Upvotes: 1

Views: 1568

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40145

try this

buffer=malloc(256);
fp=fopen("BACKING_STORE.bin", "rb");
fread(buffer, 256, 1, fp);
fclose(fp);
printf("Data=\n");
for(i = 0; i<256/sizeof(int);++i){
    printf("%d\n", buffer[i]);
}
free(buffer);

Upvotes: 1

Paul R
Paul R

Reputation: 212929

You're not printing the contents of your buffer, you're printing its address (truncated/cast to an int). Change:

printf("Data=%d\n", buffer);

to:

printf("Data=%d\n", buffer[0]);

or even

printf("Data=%d %d %d %d...\n", buffer[0], buffer[1], buffer[2], buffer[3]);

Other points to note:

  • do not cast the result of malloc in C - it's unnecessary and potentially dangerous

  • use "rb" rather than "r" when opening binary files - this does not matter on most platforms, but it can be a problem on Windows

  • always enable compiler warnings (e.g. gcc -Wall ...) - this would have enabled you to identify and fix your bugs immediately at compile-time instead of puzzling over the unexpected output at run-time

Upvotes: 2

Related Questions