2

So I'm a beginner in c and I have succeeded in writing a program for cs50 pset4 that recovers photos more specifically jpeg. However I want to test my program on something else, I mean my own deleted photos. Is it possible? If yes, how? Any help would be appreciated. This is my code:

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

int main(int argc, char *argv[])
{
    // Accepts only two command-line arguments (name of the program and name of the file)
    if (argc != 2)
    {
        printf("Usage: ./recover image");
        return 1;
    }

    //Assigning a name to argv[1]
    char *filename = argv[1];

    FILE *file = fopen(filename, "r");

    // Exiting the program if failed to open argv[1]
    if (file == NULL)
    {
        printf("Could not open %s\n", filename);
        return 2;
    }

    FILE *img = NULL;           // Name of the output file
    bool jpeg_found = false;    // Already found jpeg (false)
    unsigned char buffer[512];  // A buffer or a chunk of memory
    int imgcounter = 0;         // Calculate the number of jpegs

    // Reads the data from the file
    while (fread(buffer, 512, 1, file) == true)
    {
        // Checks the condidtions of jpeg
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            // If there is already jpeg close it
            if (jpeg_found == true)
            {
                 fclose(img);
            }

            // assign that there is a jpeg
            else
            {
                jpeg_found = true;
            }

            sprintf(filename, "%03i.jpg", imgcounter);  // Prints the name of the img files
            img = fopen(filename, "w");                 // Open img to be written
            imgcounter++;
        }

        if (jpeg_found == true)
        {
            fwrite(&buffer, 512, 1, img);
        }
    }

    fclose(img);
    fclose(file);
    return 0;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

0 Answers0