0

really tried to debug the code myself, but i really don't know what is it not working, i'm getting all 50 images, but the are all empty white images

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


int main(int argc, char *argv[]) {
    if(argc != 2) {
        fprintf(stderr, "Usage: ./recover infile\n");
        return 1;
    }
    char *infile = argv[1];
    FILE *inptr = fopen(argv[1], "r");

    if (inptr == NULL) {
        fprintf(stderr, "Could not open %s.\n", infile);
        return 2;
    }


    unsigned char buffer[512];
    int counter = 0;
    FILE* img = NULL;
    char currentBlock[10];

    while (fread(buffer, 512, 1, inptr) == 1) {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xe0) == 0xe0) {
            if (counter == 0) {
                counter++;
            }
            else {
                fclose(img);
                counter++;
            }
        sprintf(currentBlock, "%03i.jpg", counter);
        img = fopen(currentBlock, "w");
        fwrite(buffer, 512, 1, img);
        }
        else {
            if (counter != 0) {
                  img = fopen(currentBlock, "w");
                 fwrite(buffer, 512, 1, img);
            }
        }
    }
    fclose(img);
    fclose(inptr);
    return 0;
}
1

I bet that all the files are 512 bytes long too.

else {
        if (counter != 0) {
              img = fopen(currentBlock, "w");
             fwrite(buffer, 512, 1, img);
        }
    }

You have the right idea to write the blocks without signatures out after the first signature is found. The problem is in the code above. It opens the output file for EVERY block. Worse, it is opened in "w" or write mode, so the existing data is discarded.

Once a file is opened by the signature block, it doesn't need to be reopened to write to it. Just do the fwrite call.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1

You must log in to answer this question.

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