0

The code compiles and everything's good when I run it with debugger.(I set a breakpoint at the third line from the last.) But when I typed ./recover card.raw in command line and press enter, the cursor just go to the next line and no image generated in the fold. Can anyone tell me where the problem is, please? Thank you.

enter image description here

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

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

    //Check if the file can be opened
    unsigned char buffer[512];
    FILE *inptr = fopen(argv[1], "r");
    if (inptr == NULL)
        return  1;

    //Look for JPEGs
    char filename[8];
    int counter = 0;
    FILE *outptr;
    while (fread(buffer, 512, 1, inptr) == 1)
    {
        //Check whether the beginning of a JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            //Case the first JPEG
            if (counter == 0)
            {
                sprintf(filename, "%03i.jpg", counter++);
                outptr = fopen(filename, "w");
                fwrite(buffer, 512, 1, outptr);
            }
            //Case not the first image
            else
            {
                fclose(outptr);
                sprintf(filename, "%03i.jpg", counter++);
                outptr = fopen(filename, "w");
                fwrite(buffer, 512, 1, outptr);
            }
        }
        //Continue to write in privious file
        else
        {
            if (outptr != NULL)
                fwrite(buffer, 512, 1, outptr);
        }
    }

    //Close the files
    fclose(outptr);
    fclose(inptr);
}
1
  • can you format your code? – stensal Jun 4 '20 at 8:15
1

In your while loop you've set the condition to start a new file if your variable 'counter' is '0', but your forgot to set it to '0' when the end of a file is reached.

Edit: Sorry I didn't see the that following lines take care of that.

Edit2: The problem is in this line: if (outptr != NULL). You should set it to NULL when you declare it.

1
  • It works! Thank you so much! XD – Deniece-Ding Jun 4 '20 at 17:11
0

Quoting from the lecture notes -> r for read, w for write (starts writing from the beginning of the file), and a for append or adding to(starts writing at the end of the file)

You must log in to answer this question.

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