jpg 格式不正确,混合了多个图像。谁能告诉我怎么了?“恢复”

jpg's are not proper, mix of multiple images. Can anyone tell me whats wrong?“RECOVER”

我正在研究 CS50 的 PSET3 恢复。我有一个 "card.raw" 文件,其中 jpg 在第一个之后依次排列。

练习的目标是"find first jpg by scanning 512 bytes each time and checking if it is the starting of a jpg then adding next bytes to the file until next jpg start is found, then opening another file and repeating until the END OF FILE"。

图像生成不正确,我不确定我的问题出在下面的代码中。

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

int main(int argc, char *argv[])
{
    //check if program argument count is correct
    if ( argc != 2)
    {
        fprintf(stderr,"Usage: ./recover image\n");
        return(1);
    }

    char *infile = argv[1];    //Remember file name

    //open file for reading
    FILE *inptr = fopen(infile,"r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", infile);
        return(2);
    }

    typedef uint8_t BYTE;      //new name BYTE

    BYTE buffer[512];          // temporary  storage

    int counter = 0;           // image counter

    while (fread(buffer, 512, 1, inptr) == 1)
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            char filename[8];

            start:
            sprintf(filename,"%03i.jpg", counter);
            FILE *outptr = fopen(filename,"w");
            fwrite(buffer, 512, 1,outptr);

            //check next byte
             while (fread(buffer, 512, 1, inptr) == 1)
             {
                  if (buffer[0] != 0xff && buffer[1] != 0xd8 && buffer[2] != 0xff && (buffer[3] & 0xf0) != 0xe0)
                  {
                      fwrite(buffer, 512, 1,outptr);
                      printf("%i",counter);
                  }

                  //if next file starts
                  if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
                  {
                      counter++;
                      printf("%i",counter);
                      fclose(outptr);
                      goto start;
                  }
             }
             if (counter > 1)
             {
                 fclose(outptr);
             }
        }
    }
    fclose(inptr);
}

本来可以写出更好的代码,但如果它只是关于逻辑那么

if (buffer[0] != 0xff && buffer[1] != 0xd8 && buffer[2] != 0xff && (buffer[3] & 0xf0) != 0xe0)
                  {
                      fwrite(buffer, 512, 1,outptr);
                      printf("%i",counter);
                  }

这是错误的,应该是

if (!(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0))
                  {
                      fwrite(buffer, 512, 1,outptr);
                      printf("%i",counter);
                  }

因为前一个也忽略了 jpg 的任何部分,前 4 个字节中的一个或多个等于 IMG 的开始但不是全部。 谢谢大家的帮助。