0

Could you please help me to figure out what's wrong with my recover.c code? What is the reason, that only 1 JPEG is created with size of zero bytes and i get the segmentation fault error?

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

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

// ensure proper usage
if (argc != 1)
{
    printf("No command-line arguments are accepted!\n");
    return 1;
}    


// FAT block
uint8_t block[512];

// JPEG files counter
int counter = 0; 

// char-array for temporary storage of the new JPEG files names
char title[8];

FILE* outptr = 0;    


// open the CF card
FILE* inptr = fopen("card.raw", "r"); 
if (inptr == NULL)
{
    printf("Could not open card.raw.\n");
    return 2;
}

// read the CF card
fread(block, 512, 1, inptr);

// run the main loop till the end of file
while(fread(block, 512, 1, inptr) > 0)

//for (int i = 0; i < n; i++)
{

    // beginning of a JPEG detected

    if (block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] == 0xe0 || block[3] == 0xe1))
    {            

        // 0) close the currently opend JPEG file if any
        if (counter > 0)
        {
            fclose(outptr);
        }

        else
        {        
            // 1) increase JPEG files counter by 1
            counter++;

            // 2) store the file's name to the array
            sprintf(title, "%03d.jpg", counter);

            // 3) create a new JPEG file: 
            FILE* outptr = fopen(title, "w");

            // 4) write these 512 bytes to the output file
            fwrite(block, 512, 1, outptr);
        }

    }           

    // NO beggining of a JPEG detected
    else if (block[0] != 0xff && block[1] != 0xd8 && block[2] != 0xff && (block[3] != 0xe0 || block[3] != 0xe1))
    {

        // check the counter
        if (counter > 0)
        {           
            // write these 512 bytes to the currently opened output file

            fwrite(block, 512, 1, outptr);

        }

    }

 }


fclose(inptr);
return 0;

}

1 Answer 1

1

There are a number of problems that need to be dealt with. First, outptr is declared in two different places. This is causing it to go out of scope immediately, causing the seg fault. (I'm surprised you were able to compile this, as warnings are usually treated as errors, per make file settings.) Next, look at the flow when the first file has already been opened. When the next signature is found, it will close the file, but because of the else clause, it will never increment counter or do anything else in that code block.

There are more issues, but it wouldn't be right to steal all the fun. ;-) This should get you going.

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 .