I got some problems with pset4 - recover

• My code generates 27 images (instead of 50)

• those 27 images that are 'recovered' are of a weird quality. For instance; 002.jpg: 002.jpg

What are the flaws in my code? Here is the part wherein i assume it goes wrong:

    // repeat while the end of the file is not reached
    // (fread returns a size_t representing the number of elements read successfully).
    // https://stackoverflow.com/questions/15697783/how-does-fread-know-when-the-file-is-over-in-c
    while (fread(BUFFER, 1, 512, inptr_raw_file) == 512)
        // find beginning of JPEG file
        // save block as an array into a buffer variable
        // check: if buffer contains the jpeg, then execute the code below (open new file, write)
        if (BUFFER[0] == 0xff &&
            BUFFER[1] == 0xd8 &&
            BUFFER[2] == 0xff &&
            (BUFFER[3] & 0xf0) == 0xe0)
            JPEGfound = 1;
            // remove this, it is for testing purposes:
            fprintf(stderr, "JPEG start found in block\n");
            // add a counter (for the JPEG filenames)
            JPEGcounter = JPEGcounter + 1;
            //store sprintf value in a string (the JPEG name of the next file that will be made)
            sprintf(filenamestring, "%.3i.jpg", JPEGcounter);
            // create a new file using the string
            outptr = fopen(filenamestring, "w");
            // if the new file can't be made, close the inputfile and print an error
            if (outptr == NULL)
                fprintf(stderr, "Could not create %s.\n", filenamestring);
                return 3;
        if (JPEGfound == 1) // meaning a JPEG file is already found
            //write the 512 bytes into the current(!) JPEG file that is open.
            fwrite(BUFFER, sizeof (BUFFER), 1, outptr);
        else // meaning there is no JPEG found, yet
            //remove this, it is for testing purposes, N = no JPEG FOUND
            fprintf(stderr, "N");
        //move the pointer a block further (512 BYTES)
        fseek(inptr_raw_file, sizeof (BUFFER), SEEK_CUR);
    //close the input file after all blocks in the memory card are read.

Nevermind, i found the culprit myself:

Fread actually moves the pointer too, so the while (that was meant to ONLY check for the end of the file), actually made the pointer move twice as fast, compared to what i intended.

You must log in to answer this question.

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