0

Can't figure out what I'm doing wrong, I've spent like 2 days on it already, please help!

#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 == NULL)
    {
        return 1;
    }
    
    unsigned char buffer[512]; 
    FILE *img = NULL;
    int key = 0;

    while(fread(buffer, 512, 1, file) == 1)
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if (key == 0)
            {
                fclose(img);
            }
            
            char filename[8];
            sprintf(filename, "%03i.jpg", key);
            img = fopen(filename, "w"); 
            key++;
        }
        
        if (key != 0)
        {
            fwrite(&buffer, 512, 1, img);   
        }
    }
    
    fclose(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
    failed to execute program due to segmentation fault
:( recovers middle images correctly
    failed to execute program due to segmentation fault
:( recovers 049.jpg correctly
    failed to execute program due to segmentation fault
  • Perhaps it is because you didn't put a '\0' character to the end of your filenames. – MadScientist Sep 2 at 15:54
1

The code is generating a seg fault. Look at the following code:

    if (key == 0)
        {
            fclose(img);
        }

If this code is supposed to detect that a file has already been opened, shouldn't it be key > 0 ?

Weren't you seeing the seg fault when you ran the code?

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

| improve this answer | |

You must log in to answer this question.

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