0

recover.c is always producing this image: 000.jpg Here is my code:

#include <stdio.h>
#include <stdint.h>

typedef enum {false, true} bool;    // Bool

int main(int argc, char *argv[])
{
    if (argc != 2)  // Check the amount of arguments
    {
        printf("Usage: ./recover image");
        return 1;
    }
    FILE *card = fopen(argv[1], "r");   // Open card
    if (card == NULL)   // Check if card is NULL
    {
        printf("Failed to read %s", argv[1]);
        return 2;
    }

    int fileCount = 0;  // Amount of files found
    uint8_t temp[512]; // Temporary storage for each block read
    bool foundFile = false; // File found (there is random stuff before the JPEGs)
    char fname[7];
    FILE *outf = fopen("000.jpg", "w"); // Output file
    while (true)
    {
        fread(temp, 1, 512, card);  // Read 512B
        if (fread(temp, 1, 512, card) != 512)   // Check if it is the end of file
        {
            break;
        }
        if (temp[0] == 0xff & temp[1] == 0xd8 & temp[2] == 0xff &&  // Check if it is the start of JPEG
            (temp[3] >= 0xe0 & temp[3] <= 0xef))
        {
            if (fileCount != 0)
            {
                fclose(outf);   // Close preivious outf
                fileCount++;    // Increment fileCount
                sprintf(fname, "%03i.jpg", fileCount);
                outf = fopen(fname, "w");   // Open new outf
            }
            else
            {
                foundFile = true;   // File found
            }
        }
        if (foundFile)
        {
            fwrite(temp, 1, 512, outf); // Writes temp into outf
        }
    }
}
1

You fread two blocks, but fwrite one. Remove the first fread.

You don't seem to increment fileCount if it is 0. Which is a problem, as it will never leave its value of 0.

Please don't use & when dealing with conditionals, that's the bitwise AND. Use &&, the logical AND, instead. Will probably still work here, since == returns 0 or 1, even though technically any non-zero value can be interpreted as true (or rather "truthy").

Also make sure to provide eight bytes for the file name, three for the number, one for the dot, three for the file extension, one for the null terminator.

You must log in to answer this question.

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