It has been quite a struggle just to get to this point, but I feel like I'm close. Hopefully it's just a small oversight, but I keep getting 24 blank jpgs. Here's my code:

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

typedef uint8_t BYTE;

int main(void)
// open card.raw
FILE* card = fopen("card.raw", "r");

if (card == NULL)
    printf("File could not be opened.\n");
    return 1;

// set output file
FILE* out = NULL;

// set array for jpg file names
char temp[10];

// create buffer of 512 bytes
BYTE buffer[512];

// create counter for jpgs
int jpg = 0;

// loop to read card until end of card
while (!feof(card))
    // read 512 byte block into buffer
    fread(buffer, sizeof(buffer), 1, card);

    // determine if block is a jpg
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff
            && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
        if (out == NULL)
            // name file with 3 digits (00X)
            sprintf(temp, "%03d.jpg", jpg);

            // open file to write to
            out = fopen(temp, "w");

            // write buffer to jpg file
            fwrite(buffer, sizeof(buffer), 1, out);

            // move counter up for next file number
            out = NULL;


Your code looks for a signature at the beginning of a block. Since it appears to be creating a number of files, that part seems to be working, sort of.

Creating 24 files? Hmmm, that's a problem. If no file is open, it will open a file. If it finds a signature and an output file is open, it closes it and moves on to the next block. So, it looks to me that every other file is lost.

Empty files? I bet that you're creating 24 files of 512 bytes each. The first block with the signature is being written out to the output file. What about all of the blocks in between? JPEG files can be of just about any size, but only the first block is going to have the signature (except by sheer chance.)

Finally, you are checking for 2 signatures (as described in Zamyla's video from last year.) This year's problem says to check for 16 different signatures. The spec is in the pset instructions, not the videos. ;-)

Oh yeah, wait till you solve all those problems and check50 tells you there's a problem with the last file. I'll let you sort that one out on your own :-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

  • Yes, thank you so much. You're answer really got me thinking and I was able to figure it out (basically the problem was in your second paragraph it seems). I haven't done check50 yet, though I do realize there will be some issues. Mar 25 '16 at 2:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .