0

I keep looking my code and connot identify what is going on. I open 22 pictures, but none of them are good. It doesn't even write in the entire picture, some of them just a part of the picture is written. The very first row seems to be a little more visible but it is hard to tell.

int main(int argc, char *argv[]) { if (argc != 2) //Check if user enter the file { printf("Usage: ./recover image\n"); }

// Opening file suer entered

FILE *file = fopen(argv[1], "r");
 if (file == NULL)
 {
     printf("File could not be opened");
     return 1;
 }


uint8_t block[512]; //Buffer to read each block
char newfile[8]; //name of new jpeg
int fn = 0;  //nuber to name each jpeg
FILE *filejpg = NULL; //new jpg as a file



while (fread(block, 512, 1, file) == 1)
{
    fread(block, 512, 1, file);  //reading the file

    if (block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && ((block[3] & 0xf0) == 0xe0))   //check to see if the block contains the header of jpeg
    {
        if (fn == 0)
        {
            sprintf(newfile, "%03i.jpg", fn); //naming the new file
            fn ++; //increase the name for the next file

            filejpg = fopen(newfile, "w");  //Opening the file to write
            fwrite(block, 512, 1, filejpg);  //Writing the data to the file
        }
        else
        {
            fclose(filejpg); //closing last image
            sprintf(newfile, "%03i.jpg", fn);
            fn++;

            filejpg = fopen(newfile, "w");
            fwrite(block, 512, 1, filejpg);
        }
    }
    else if (fn > 0)  //writing on image one block at a time until new jpg is found.
    {
        fwrite(block, 512, 1, filejpg);
    }
}// end while loop

fclose(filejpg);
fclose(file);

return 0;

}//end of function

1 Answer 1

0

Is there a reason that you want to do two consecutive reads and throw one of them away?

while (fread(block, 512, 1, file) == 1)
{
    fread(block, 512, 1, file);  //reading the file

This is a very common error. For full details, please read one of the other answers for similar questions.

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 .