Shredder2794 Shredder2794 - 12 days ago 6
C Question

fread into buffer is blank despite non-empty file

I'm trying to read in 256 bytes into a buffer from a 65536 byte file, treating it as a random-access file by using fopen, fread, fwrite, and fseek. I'm not getting any errors, but the buffer is still empty after the read, even though the file is non-empty and fread reports reading 256 bytes. Here's my code:

FILE *file = NULL;
char buffer[255];
memset(buffer, 0, sizeof(buffer));

file = fopen("BACKING_STORE.bin","r");

if(file == NULL) {
printf("Error: can't open file.\n");
return NULL;
} // end if

if(fread(buffer, 1, 256, file) != 256) {
printf("Error: reading from file failed.\n");
return NULL;
} // end if

printf("The bytes read are [%s]\n", buffer);

fclose(file);


And just to confirm, I opened up the BACKING_STORE.bin file in a hex editor just to make sure that it wasn't empty. Here's a screenshot of that:
enter image description here

After running this program, I get the output: "The bytes read are []" but without any errors.

I'm fairly new to C, so I'm sure it's just something simple I'm missing.

Thanks for the help. :)

Answer

Because you can't output binary data with "%s" and printf(). If you want to see the contents you can write a loop and print the hex value of each byte, like this

for (size_t i = 0 ; i < 256 ; ++i) {
    fprintf(stdout, "0x%02x ", buffer[i]);
    if ((i + 1) % 8 == 0) {
        fputc('\n', stdout);
    }
}