Search code examples
cprintffwritefreadcs50

How to print contents of buffer in C?


C newbie here working on problem set 4 of CS50, where you are given a memory card to recover 50 jpeg files.

I'm trying to read the raw data 512 bytes at a time, but I would like to know how to I can print the contents of each 512 byte block ?

My method of using fwrite doesn't seem to be printing anything in this instance:

fread(buffer, 512, 1, inptr);

fwrite(buffer, 1, 512, stdout);

Rest of code:

#include <stdio.h>
#include <stdint.h>

int main(int argc, char *argv[])
{
    // Ensure only 1 command-line argument
    if (argc != 2)
    {
        fprintf(stderr, "Usage: ./recover infile");
        return 1;
    }

    // Remember filename
    char *infile = argv[1];


    // Open input file
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", infile);
        return 2;
    }

    // Create buffer to store 8 bits 512 times
    uint8_t buffer[512];

    fread(buffer, 512, 1, inptr);

    fwrite(buffer, 1, 512, stdout);

    // Close infile
    fclose(inptr);

    return 0;
}

Solution

  • A JPEG file contains binary data, so you can't print it the same way you would print a string.

    What you probably want is to print the hex value of each byte you've read. You can do that as follows:

    for (i=0; i<512; i++) {
        printf("%02x ", buffer[i]);
        if ((i+1)%16 == 0) printf("\n");
    }
    

    This will print each byte in hex, with 16 bytes written per line.