首页 > 解决方案 > CS50 的 PSET 3 - Recover.c - 我的 JPEG 文件已恢复,但它们都是空的

问题描述

所以我目前正在尝试从 cs50 pset3 恢复.c,并且我已经恢复了所有 49 个 jpeg 文件。但是,所有这些 jpeg 文件都是空的(带有灰色和白色网格)。有人可以解释我的代码哪里出错了吗?我尝试了 check50 来查看我的代码是否正确,但它说恢复的图像不匹配。

我也在我的 fopen 函数中将我的“w”更改为“wb”,但这似乎也不起作用。

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

int main(int argc, char *argv[])
{
//a data type that can store a byte
typedef uint8_t BYTE;

//Checking to see if there is only one command line argument
if (argc != 2)
{
    fprintf(stderr, "Usage: ./recover image\n" );
    return 1;
}

//Opening the file to see if its correct

char *infile = argv[1];
FILE *memory = fopen(infile, "r");
if (memory == NULL)
{
    fprintf(stderr, "Could not open %s.\n", infile);
    return 2;
}

//Creation of a buffer
BYTE buffer[512] = {0};
//Whether or not we have found a JPEG or not
bool jpegfound = false;
//the number of JPEG files found
int numJPEGfile = 0;
//declaring the new to be JPEG file so that it has a scope for the 
whole while loop
FILE *img = NULL;
//declaring the new JPEG filename
char filename[8];

//Repeating until the end of card
while(fread(buffer, 512, 1, memory) == 1)
{

    //Start of a new JPEG?
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
    {
        jpegfound = true;
        sprintf(filename, "%03i.jpg", numJPEGfile);
        numJPEGfile += 1;
        img = fopen(filename, "wb");
        fwrite(buffer, 512, 1, img);

    }

    //Have we already found a JPEG?
    if(jpegfound)
    {
        jpegfound = false;
        fclose(img);

    }


}

//Close any remaining files
fclose(memory);
return 0;

}

标签: jpegcs50

解决方案


如果您在终端中运行以下命令,您恢复的 jpg 文件有多大?我认为这将为您提供解决此 pset 的提示。

ls -l

推荐阅读