0

Having an incredibly tough time figuring out where my error is. The JPEG outputs look good but when I do check 50, I'm getting a

:( for "recovers 049.jpg correctly - recovered image does not match.

I've tried switching my while loop to while (fread(buffer, 1, 512, inptr) == 512) but it messes up all of my pictures and I have no idea why. Help, please!

while (!feof(inptr))
    {
        // read 512 bytes into a buffer
        fread(buffer, 1, 512, inptr);

        // determine if it is a start of a JPEG
        if (buffer[0] == 0xff &&
            buffer[1] == 0xd8 &&
            buffer[2] == 0xff &&
            (buffer[3] & 0xf0) == 0xe0)
        {
            // Is a JPEG open?
            if (img != NULL)
            {
                // If a JPEG is open, close the file
                fclose(img);
                img = NULL;
            }

            // If a JPEG is not already open, create a new file and begin writing to the file
            sprintf(filename, "%03i.jpg", i);
            img = fopen(filename, "w");
            fwrite(buffer, 1, 512, img);
            i++;
        }

        // if not a start of a JPEG, is a JPEG already open?
        else if (img != NULL)
        {
            // if a JPEG is open, continue writing to the JPEG
            fwrite(buffer, 1, 512, img);
        }
    }
2

Look at this code and think about what it does:

while (!feof(inptr))
    {
        // read 512 bytes into a buffer
        fread(buffer, 1, 512, inptr);
    ....
    }

It checks the input file for EOF and then it reads in and processes the next data block. Now, what happens at the end of the input file? It reads the last 512 byte block, adds it to the output file, loops back to the top to see that the end of file hasn't been reached, and starts the loop again. It does one final read, but reads 0 bytes because now, it has reached the EOF. The read actually reads nothing, so the buffer remains unchanged from the last read. So, the code that follows ends up writing that previous 512 byte block to the output file a second time. (This is why your file doesn't match the correct solution.) Now, the loop goes back up, checks that the EOF has been set, and the loop exits.

You have to understand how EOF works. The EOF flag isn't set for a file until the end of the file has been passed. You can read right up to and including the last byte in a file, but that won't set EOF until you try to go past that last byte. A good analogy is this. A blind person can walk all the way out to the end of a diving board. As long as he stays on the diving board, his feet stay dry. But take one step past the end, his feet get wet!(EOF!)

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

You must log in to answer this question.

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