cs50恢复,“恢复的图像不匹配”

时间:2020-04-22 06:15:23

标签: c cs50 recover

我的源代码成功编译并生成了50张图片。
但是,没有恢复的图像与原始图像匹配。
所有jpeg如下所示。
如您所见,它们似乎有奇怪的边缘重叠。
其中一些看起来还不错,但仍然无法匹配原始图片。

enter image description here enter image description here

如果您可以提供有关调试的任何见解,请告诉我。

这是我的代码

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

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./recover image\n");
        return 1;
    }

    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
    {
        printf("Could not open %s.\n", argv[1]);
        return 1;
    }

    typedef uint8_t BYTE;
    BYTE buffer[512];
    char *filename[8];
    int jpeg_counter = 0;
    bool foundStartOfJPEG = false;
    FILE *img;

    // read memory card until the end of file
    while(fread(buffer, sizeof(BYTE) * 512, 1, file) == 1)
    {
        // if buffer has a signature of JPEG file,
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && ((buffer[3]) & 0xf0) == 0xe0)
        {
            if (foundStartOfJPEG == true)
            {
                fclose(img);
                jpeg_counter += 1;
            }

            foundStartOfJPEG = true;
            // create a file with index
            sprintf(*filename, "%03i.jpg", jpeg_counter);
            // open that file to write into it
            img = fopen(*filename, "w");
            // write the block of memory (buffer), to that file
            fwrite(buffer, sizeof(buffer), 1, img);
        }
        else if (foundStartOfJPEG == true)
        {
            fwrite(buffer, sizeof(buffer), 1, img);
        }
    }

    fclose(file);
    return 0;
}

2 个答案:

答案 0 :(得分:1)

我尝试了您的代码,当您将文件名从指针更改为数组(即char *文件名更改为char文件名)时,它可以工作。

答案 1 :(得分:1)

这也可以使用,并且结合了指针的使用。这里的p是一个指向文件名的指针。但是,我认为它的使用是多余的。完全不用p的情况下,您可以说filename是指向filename的第一个元素即filename [0]的指针。因此,当您使用char * filename [8]时,就像说filename是一个指向指针的指针一样……希望有道理!

typedef uint8_t BYTE;
BYTE buffer[512];
char filename[8];
char *p = filename;
int jpeg_counter = 0;
bool foundStartOfJPEG = false;
FILE *img;

// read memory card until the end of file
while(fread(buffer, sizeof(BYTE) * 512, 1, file) == 1)
{
    // if buffer has a signature of JPEG file,
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && ((buffer[3]) & 0xf0) == 0xe0)
    {
        if (foundStartOfJPEG == true)
        {
            fclose(img);
        }

        jpeg_counter += 1;
        foundStartOfJPEG = true;
        // create a file with index
        sprintf(p, "%03i.jpg", jpeg_counter);
        // open that file to write into it
        img = fopen(p, "w");
        // write the block of memory (buffer), to that file
        fwrite(buffer, sizeof(buffer), 1, img);
    }
    else if (foundStartOfJPEG == true)
    {
        fwrite(buffer, sizeof(buffer), 1, img);
    }
}