Search code examples
cbinaryfopenfread

C : Reading bytes from binary file


I am currently trying to read 256 bytes from a binary file and not getting any output (or errors) when running my program. I am a little confused where I am going wrong on this. Attempting to read each byte as a char and store as a char array of length 256. I have reviewed similar questions on SO already and haven't had any luck so far. Simplified version of my code below:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]){
    FILE *binary = fopen(argv[1], "rb");
    char bytesFromBinary[256];

    fread(&bytesFromBinary, 1, 256, binary);
    printf("%s", bytesFromBinary);
    return 0;
}

Solution

  • A basic use of fread will check the return against the number of bytes expected to validate you read what you intended to read. Saving the return allows you to handle partial reads as well.

    The following minimal example reads 16-bytes at a time from the file given as the first argument (or stdin by default if no file is given) into buf and then outputs each value to stdout in hex-format.

    #include <stdio.h>
    
    #define BUFSZ 16
    
    int main (int argc, char **argv) {
    
        unsigned char buf[BUFSZ] = {0};
        size_t bytes = 0, i, readsz = sizeof buf;
        FILE *fp = argc > 1 ? fopen (argv[1], "rb") : stdin;
    
        if (!fp) {
            fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
            return 1;
        }
    
        /* read/output BUFSZ bytes at a time */
        while ((bytes = fread (buf, sizeof *buf, readsz, fp)) == readsz) {
            for (i = 0; i < readsz; i++)
                printf (" 0x%02x", buf[i]);
            putchar ('\n');
        }
        for (i = 0; i < bytes; i++) /* output final partial buf */
            printf (" 0x%02x", buf[i]);
        putchar ('\n');
    
        if (fp != stdin)
            fclose (fp);
    
        return 0;
    }
    

    (note: bytes == readsz only when the size parameter to fread is 1. The return is the number of items read and each item is only equal to 1 for char type values)

    Example Use/Output

    $ echo "A quick brown fox jumps over the lazy dog" | ./bin/fread_write_hex
     0x41 0x20 0x71 0x75 0x69 0x63 0x6b 0x20 0x62 0x72 0x6f 0x77 0x6e 0x20 0x66 0x6f
     0x78 0x20 0x6a 0x75 0x6d 0x70 0x73 0x20 0x6f 0x76 0x65 0x72 0x20 0x74 0x68 0x65
     0x20 0x6c 0x61 0x7a 0x79 0x20 0x64 0x6f 0x67 0x0a
    

    Look over the example and let me know if you have any questions.