EDX CS50x PSET3 recovery.c(恢复的图像不匹配:仅适用于049.jpg文件)

时间:2019-03-16 23:04:43

标签: c jpeg cs50 image-size recover

我陷入了这个问题:

结果: :) recovery.c存在。 :) recovery.c编译。 :)处理缺乏取证图像 :)正确恢复000.jpg :)正确恢复中间图像 :(可正确恢复049.jpg     恢复的图片不匹配

该文件可以正确编译,并且所有50个.jpg文件都清晰可见,但是最后一个文件存在这个小问题(049.jpg:恢复的图像不匹配),我只是无法弄清原因。

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

int main(int argc, char *argv[])
{
    // ensure 1 command-line argument:
    if(argc != 2)
    {
        fprintf(stderr, "Usage: name of forensic image from which to recover JPEGs");
        return 1;
    }
    // open the memory card file:
    FILE *file = fopen(argv[1], "r");
    if (!file)
    {
        fprintf(stderr, "Could not open %s.\n", argv[1]);
        fclose(file);
        return 2;
    }
    //fseek(file, 0, SEEK_SET);
    unsigned char buffer[512];
    char* filename = malloc(50 * sizeof(int));
    if (!filename)
    {
        return 3;
    }
    bool jpeg_found = false;
    int f = 0;
    int n = 0;

    while (!(feof(file)))
    {
        sprintf(filename, "%03i.jpg", f);
        FILE *img = fopen(filename, "w");
        if (!filename) return 6;
        if (f > 0) fwrite(buffer, 1, 512, img);
        n = 0;

        while (n == 0)
        {
            if (feof(file))
            {
                fclose(img);
                break;
            }
            fread(buffer, 1, 512, file);    //read 512 bytes into a buffer
            if (buffer[0] == 0xff &&        // start of a new JPEG?
            buffer[1] == 0xd8 &&
            buffer[2] == 0xff && (
            buffer[3] & 0xf0) == 0xe0)
            {
                if (jpeg_found) // have you already found a JPEG or not?
                {
                    // YES: close the previous file and open a new one,
                    fclose(img);
                    f += 1;
                    n = 1;
                }
                else // NO: start very 1st JPEG
                {
                    fwrite(buffer, 1, 512, img);
                    jpeg_found = true;
                }
            }
            else
            {
                if (jpeg_found) // Have your already found a JPEG or not?
                {
                    // YES: Those 512 bytes belong to the current opened JPEG file
                    fwrite(buffer, 1, 512, img);
                }
                else  // NO: Discard the 512 bytes and go to the start of the loop
                {
                    continue;
                }
            }
        }
    }
    free(filename);
    fclose(file);

0 个答案:

没有答案