0

This is the code:

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

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        return 1;
    }
    
    FILE *file = fopen(argv[1], "r");
    
    if (!file)
    {
        return 1;
    }
    
    unsigned char buffer[512]; 
    int key = 0;
    
    FILE *img = NULL;

    while(fread(buffer, sizeof(unsigned char), 512, file) == 1)
    {
        fread(buffer, sizeof(unsigned char), 512, file);
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            key++; 
            if (key == 1)
            {
                fclose(img);
            }
            
            char filename[8];
            sprintf(filename, "%03i.jpg", key);
            img = fopen(filename, "a"); 
        }
        
        if (key != 0)
        {
            fwrite(&buffer, sizeof(unsigned char), 512, img);   
        }
    }
    
    fclose(file);
    return 0;
}

This is the error I get:

:) recover.c exists.
:) recover.c compiles.
:) handles lack of forensic image
:( recovers 000.jpg correctly
    000.jpg not found
:( recovers middle images correctly
    001.jpg not found
:( recovers 049.jpg correctly
    049.jpg not found

1 Answer 1

0
while(fread(buffer, sizeof(unsigned char), 512, file) == 1)
{
    fread(buffer, sizeof(unsigned char), 512, file);

The code is executing two consecutive freads without processing the data from the first read. That means that all the data from the first read is being thrown away without being processed.

It's a common misconception that an fread in a while or an if statement only generates a return value to be tested. This is wrong. In order to get that value to be tested, it is executing the read first.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • Thank you so much for your suggestion. There seems to be another problem. I'm still getting the same error even after I removed the fread() after the while statement and kept only the one inside it. Is there anything else that I'm doing wrong? Aug 27, 2020 at 11:56
  • at a quick glance, I see two problems. FIrst, the output files are being opened for append and not for write. If a file already exists, it'll just add to it. Second, key is incremented before being checked, so when the first file is opened, it attempts to close the previous file even though there is no open file. And, it'll never close any later files because the code is checking if key == 1, It should be checking if it's greater than or equal to 1.
    – Cliff B
    Aug 27, 2020 at 18:06

You must log in to answer this question.

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