0

I have successfully (or I guess not super successfully) recovers all 50 images, but where am I going wrong? Thanks!

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

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

    // open file
    FILE *file = fopen(argv[1], "r");

    // make sure it's a valid file
    if (file == NULL)
    {
        printf("Could not load file!\n");
        return 2;
    }

    // create array with size of 512 bytes to read
    // initialize counter and file pointer
    unsigned char buffer[512];
    int JPEG_counter = 0;
    FILE *img = NULL;
    char filename[8];

    // read until end of memory card, aka read 512 bytes while they are there to read
    while (fread(buffer, 512, 1, file) == 1)
    {
            // while reade if JPEG header is found, counter increases
            if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
            {
                if (JPEG_counter > 0) // if it's not first jpeg, the previous one must be closed then create new one
                {
                    fclose(img);
                }

                JPEG_counter++;
                sprintf(filename, "%03i.jpg", JPEG_counter);
                img = fopen(filename, "w");
                fwrite (buffer, 512, 1, img);
            }
            else
            {
                if (JPEG_counter > 0)
                {
                // if the bit of byte isn't a beginning of JPEG then it must be continuously written onto
                    fwrite (buffer, 512, 1, img);
                }
            }
        }

    fclose(file);

}

1

From the spec hints:

Your program should number the files it outputs by naming each ###.jpg, where ### is three-digit decimal number from 000 on up.

This program will name the first file 001.jpg.

1
  • Seems like I had just stared myself blind on the problem, thanks for your time!
    – HoopsLoops
    May 19 '20 at 23:01

You must log in to answer this question.

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