1

My code for recover.c works except for 015.jpg. I can see the image in the folder, but the file is not closing correctly and thus disrupting check50.

I get that I want to put a "forever loop" somewhere in my code to exit out of the current chunk when the buffer contains less than 512 bytes. But I am a bit confused as to where to put this and how to implement it.

I know I should be doing something along the lines of:

while (fread(&buffer, 512, 1, file) == 1)
{
    // execute code
}

fclose(img);

I thought my code implicitly does this and why I have fclose(img) at the end of my for loop.

Here is my code:

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

int main(int argc, char* argv[])
{
// open memory card file
FILE* file = fopen("card.raw", "r");
if (file == NULL)
{
    printf("Could not open file\n");
    return 1;
}

// create a buffer
unsigned char buffer [512];

// create a file namefor jpgs
char jpgname [8];

// search for start of jpgs
while (buffer[0] != 0xff || buffer[1] != 0xd8 || buffer[2] != 0xff || (buffer[3] != 0xe0 && buffer[3] != (0xe1)))
{  
    fread(&buffer, 512, 1, file);
}

// create new file for each jpg and write jpg to new file
for (int i = 0; i < 17; i++)
{      
    // create file name with %03d to get ###.jpg
    sprintf(jpgname, "%03d.jpg", i);

    // create files
    FILE* img = fopen(jpgname, "w");

    // determine if file is NULL
    if (img == NULL)
    {
        fclose(file);
        printf("File can't be created");
        return 2;
    }

    // write from the card's buffer to the jpg img file
    fwrite(&buffer, 512, 1, img);
    if (feof(file))
        break;
    if (fread(&buffer, 512, 1, file) != 1)
    {
        fwrite(&buffer, 512, 1, img);
        break;
    }

    // find the start of the next jpg
    while (buffer[0] != 0xff || buffer[1] != 0xd8 || buffer[2] != 0xff || (buffer[3] != 0xe0 && buffer[3] != 0xe1))
    {
        fwrite(&buffer, 512, 1, img);
        if (fread(&buffer, 512, 1, file) != 1)
        {
            fwrite(&buffer, 512, 1, img);
            break;
        }
    }  

    // close jpg image file
    fclose(img);
}

// close any remaining files  
fclose(file);

// that's it!
return 0;  
}

Thanks in advance for the help!

1 Answer 1

1

Figured it out. I was continuing to write even though the file ended. I deleted one of my fwrite statements and the problem was fixed!

You must log in to answer this question.

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