0

When I run the following code, it doesn't appear as if my while loop is being invoked because it never prints the print statement, but I cannot find a reason why it is not running the while loop.

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

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./recover image\n");
        return 1;
    }
    
    FILE *f = fopen(argv[1], "r");
    
    if (f == NULL)
    {
        printf("File could not be opened\n");
        return 1;
    }
    
    unsigned char buffer[512];
    int count = 0;
    char filename[8];
    FILE *recovered = NULL;
    
    while (fread(buffer, 512, 1, f) == 1)
   {
       printf("hi\n");

    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if (count > 0)
            {
                fclose(recovered);
            }
            
            count++;
            recovered = fopen(filename, "w");
            sprintf(filename, "%03i.jpg", count);
            fwrite(f, 512, 1, recovered);
            printf("HI");
        }
   }
    
    fclose(f);
    fclose(recovered);
}

1 Answer 1

0

Did you remember to recompile the program? You probably did.

Or, more likely, you're just not seeing "HI" before it scrolls away. The code is printing "hi" and "HI" for me! You might want to comment out the lower case hi printf. There are hundreds of them and they're making the uppercase HI scroll off the screen.

The while loop is definitely being executed, and it looks like it's executing correctly and the correct number of times.

Once you get past that, there are two other issues. First, the intermediate 512 byte data blocks between signatures aren't being added to output files. Second, output files should start with 000, not 001.

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 .