0

I've been staring at this for a couple hours and I still can't figure out what's wrong with it! After executing it, it gives me 50 pictures but they're either blurry or black and white checkered. I was thinking maybe it has something to do with the condition while(fread(buffer, 512, 1, inptr) != 0);, but it could be something else completely. Thanks in advance!

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

typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: ./recover\n");
        return 1;
    }

    BYTE buffer[512];

    char *infile = argv[1];
    FILE *inptr = fopen(infile, "r");

    if(!inptr)
    {
        return 1;
    }

    FILE *image = NULL;
    int numPics = 0;

    do
    {
        fread(buffer, 512, 1, inptr);

        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && ((buffer[3] & 0xf0) == 0xe0))
            // (buffer[3] == 0xe0 || buffer[3] == 0xe1 || buffer[3] == 0xe2 || buffer[3] == 0xe3 || buffer[3] == 0xe4 ||
            // buffer[3] == 0xe5 || buffer[3] == 0xe6 || buffer[3] == 0xe7 || buffer[3] == 0xe8 || buffer[3] == 0xe9 ||
            // buffer[3] == 0xea || buffer[3] == 0xeb || buffer[3] == 0xec || buffer[3] == 0xed || buffer[3] == 0xee ||
            // buffer[3] == 0xef))
            //0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, of 0xef
        {
            if (numPics >= 1)
            {
                fclose(image);
            }

            char filename[8];
            sprintf(filename, "%03i.jpg", numPics);
            image = fopen(filename, "w");

            fwrite(buffer, 512, 1, image);
            numPics++;
        }
    }
    while(fread(buffer, 512, 1, inptr) != 0);

    fclose(inptr);
    fclose(image);

    return 0;
}

1 Answer 1

0

Two problems. First, there are effectively two back-to-back freads - one at the end of the loop immediately followed in processing by the one at the start. This effectively throws away half of the data.

Second, what happens to all of the image data between blocks with signatures? The code only seems to be writing data blocks with signatures. A jpeg file can be any size, not just 512 bytes. Suggest you run ls -al *.jpg in your directory.

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 .