0

I have problemes with my code for Recover. It compiles ok but when i try it I have a segmentation fault. So i looked with debug50 and it seems that my if conditions is never true, so my code just go to the else and then causing the segmentation fault as it tries to write something that don't existe.

I don't see why the if conditions is problematic here, could someone give me an hint ?

Thanks

#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>

int main(int argc, char *argv[])
{

unsigned char buffer[512]; //buffer to copy bloc of 512 bytes
char filename[8]; //array to store filename
int counter = 0; //count number of jpeg found
bool jpegfound = false; //bool to know if first jpeg is found

    //check if correct format
    if (argc != 2)
    {
        printf("Correct usage : memory card name\n");
        return 1;
    }
    //open files and check if it can open
    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
    {
        fclose(file);
        printf("Error impossible to open file\n");
        return 1;
    }

FILE *outptr = NULL; //file for recover images

while(fread(buffer, 1, 512, file) == 512) //loop while fread return value equal to 512
{
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
    {
        if ((jpegfound = false)) //if it the first jpeg
        {
        //open new file to write jpeg to, sprintf to name it, fopen to open it, fwrite to write into it
        sprintf(filename, "%03i.jpg", counter);
        outptr = fopen(filename, "w");
        fwrite (buffer, sizeof(char), 512, outptr);
        jpegfound = true;
        }

        else // if it is not the first jpeg
        {
        fclose (outptr); //close previous jpeg
        counter++; //update counter
        sprintf(filename, "%03i", counter); //begin to write into a new file
        outptr = fopen(filename, "w");
        fwrite(buffer, sizeof(char), 512, outptr);
        }
    }
    else
    {
        if ((jpegfound = true)) //continue writing into the file
        {
            fwrite(buffer, sizeof(char), 512, outptr);
        }
        else
        {
            printf("rien");
        }
    }
}

fclose(outptr);
fclose(file);
return 0;


}
```
1

This if ((jpegfound = true)) is going to set jpegfound to true, not compare jpegfound to true. The proper syntax for equality in an if statment uses ==.

  • Thank you so much , i was far away to find this ! – Martinf May 5 '20 at 8:44

You must log in to answer this question.

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