0

Recover.c

I have written code of recover.c of pset4. Every time I compile it, everything seems fine but when I run it using: ./recover card.raw, I get a new line with no files created. Why is this? Here's my code:

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

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        fprintf(stderr, "Usage: ./recover file");
        return 1;
    }

    char *infile = argv[1];

    FILE *in = fopen(infile, "r");
    if(in == NULL)
    {
        fprintf(stderr, "%s couldn't be opened\n", infile);
        fclose(in);
        return 2;
    }

    int count = 0;
    uint32_t buf[512];
    char a[8];
    FILE *out;

    while(fread(&buf, 512, 1, in) == 1)
    {
        if(buf[0] == 0xff && buf[1] == 0xd8 && buf[2] == 0xff && (buf[3] == 0xe1 || buf[3] == 0xe2 || buf[3] == 0xe3 || buf[3] == 0xe4 || buf[3] == 0xe5 || buf[3] == 0xe6))
        {
            sprintf(a, "%03d.jpg", count);
            count++;
            out = fopen(a, "w");
            if(out == NULL)
            {
                fprintf(stderr, "Error\n");
                fclose(out);
                return 3;
            }
            fwrite(&buf, 512, 1, out);
            fclose(out);
        }

        else
        return 4;
    }

    fclose(in);

    printf("process complete\n");

    return 0;
}

1 Answer 1

3

I too have been having the same issue, but I would suggest a few edits that may help get your code working.

  1. The biggest issue I see with your code right now is that, after checking the first 512-bytes-long block, you either start writing a JPEG, or you return with code 4. What if the JPEG starts later in the card, and not in the first block?
  2. Remember, a JPEG can be longer than 512 bytes. Currently, you are only writing the first 512 bytes after the header to the outfile, and then closing the outfile.
  3. Your if statement does technically get the job done, but if you refer to the problem walkthrough at https://www.youtube.com/watch?v=hOWYGowwId0, you will see that there is a much more concise way to check the fourth byte of the if condition, which cuts down on possibilities for error.

You must log in to answer this question.

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