0

I've been stuck on Recover for the last few days. I'm trying to work out why Submit tells me none of the jpg files are found. I've revised it multiple times, worked it out on paper... I can't figure out what the problem is. Any help would be greatly appreciated!

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

typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: ./recover image\n");
        return 1;
    }
    char *infile = argv[1];
    FILE *cardfile = fopen(infile, "r");
    if (infile == NULL)
    {
        fprintf(stderr, "Could not open %s", infile);
        return 2;
    }
    int r = 0;
    int jpgcount = 0;
    int c;
    char filename[8];
    FILE *jpgfile = NULL;
    unsigned char bytes[512];

    while((c = fgetc(cardfile)) != EOF)
    {
        fread(bytes, sizeof(BYTE), 512, cardfile);
        if (bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff && (bytes[3]==0xe0 || bytes[3]==0xe1))
            {
                if(jpgcount >= 1)
                {
                    fclose(jpgfile);
                    r++;
                }
                sprintf(filename, "%03i.jpg", r);

                jpgfile = fopen(filename, "w");
                if (jpgfile == NULL)
                {
                    fprintf(stderr, "Could not create %s.\n", filename);
                    return 3;
                }
                jpgcount++;
            }
        if(jpgcount == 0)
        {
            continue;
        }
            fwrite(bytes, sizeof(BYTE), 512, jpgfile);
    }
    fclose(cardfile);
    if(jpgfile != NULL)
    {
        fclose(jpgfile);
    }
    return 0;
}

1 Answer 1

1

This is the problem. You read one char from the cardfile, but this char is never processed as part of the bytes. Basically, you just drop these chars.

   while((c = fgetc(cardfile)) != EOF)
    {
2
  • Thank you! Really appreciate it. Wow, that was all it was huh. I sort of understand what you're saying, but I'm not sure how to go about making it work. I changed c from an int, to an unsigned char, to a signed char. I pretty much followed the format that Doug lays out in the File Pointers video, right> Regardless, I just gave up on using fgetc completely and did a simple while(p > q). Anyways, thanks again! Commented May 30, 2020 at 2:09
  • You don't need fgetc, just check the return value of fread to decide whether you should terminate a loop.
    – stensal
    Commented May 30, 2020 at 3:59

You must log in to answer this question.

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