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

typedef unsigned char BYTE;

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        return 1;
    }
    FILE *infile = fopen(argv[1], "r");
    FILE *recovered = NULL;
    char *filename = malloc(sizeof(char) * 8);

    BYTE buffer[512];

    int index = -1;
    size_t read = -1;
    while (read != 0 && !feof(infile))
    {
        read = fread(buffer, 512, 1, infile);
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if (index == -1)
            {
                index++;
                sprintf(filename, "%03i.jpg", index);
                recovered = fopen(filename, "w");
                if (!recovered)
                {
                    printf("could not open file: %s", filename);
                    return 1;
                }
                fwrite(buffer, 1, 512, recovered);
            }
            else if (index != -1)
            {
                index++;
                fclose(recovered);
                sprintf(filename, "%03i.jpg", index);
                recovered = fopen(filename, "w");
                if (!recovered)
                {
                    printf("could not open file: %s", filename);
                    return 1;
                }
                fwrite(buffer, 1, 512, recovered);
            }
        }
        else if (index != -1)
        {
            fwrite(buffer, 1, 512, recovered);
        }
    }
    free(filename);
    fclose(infile);
    fclose(recovered);
    
}
0

"READY, FIRE, AIM!"

The code reads in 512 bytes, then writes it out to the output file and then checks for EOF. Here's the thing. The EOF condition isn't set until an attempt is made to read beyond the end of the file. If the last byte is read, but no further read is attempted, EOF is not set.

So, the while loop executes one more time. It attempts to read 512 bytes beyond the end of the file. The read fails, so the buffer remains unchanged from the last read. Those 512 bytes are written to the output file a second time, meaning the file is too big by 512 bytes. On the next pass, the EOF condition is set, so the loop finally terminates, but the damage has been done.

The code is checking the return value from the read, eventually. Have you considered doing the read inside the while loop statement?

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 .