【问题标题】:PSET4 RECOVERY does not recover images correctlyPSET4 RECOVERY 无法正确恢复图像
【发布时间】:2021-08-06 01:20:34
【问题描述】:

我已经开始研究 PSET 4 RECOVERY。我的程序编译成功,它通过了前 3 次测试没问题,但是为了我的爱,我似乎找不到问题所在。 它只是无法正确恢复照片,我尝试将 ptr 更改为 char 反之亦然无济于事。

代码如下:

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

typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
    //check for number of arguments
    if (argc != 2)
    {
        printf("Usage: ./recover filename\n");
        return 1;
    }
    //initialize files
    char *input_name = argv[1];
    FILE *input = fopen(input_name, "r");
    if (input == NULL)
    {
        //check if file is openable
        printf("File %s could not be opened!", input_name);
        return 1;
    }
    //initialize files and pointers
    BYTE file[512];
    int counter = 0;
    FILE *img = NULL;
    char img_name[8];
    //loop as long as files returns bytes
    while(fread(&file, 512, 1, input) == 1)
    {
        //check if file is jpeg
        if (file[0] == 0xff && file[1] == 0xd8 && file[2] == 0xff && (file[3] & 0xf0) == 0xe0)
        {
            //if a previous file is open, close it
            if (counter != 0)
            fclose(img);
        }
        //initialize new file
        sprintf(img_name, "%03i.jpg", counter);
        img = fopen(img_name, "w");
        counter++;
        //if jpeg is found, write
        if (counter != 0)
        {
            fwrite(&file, 512, 1, img);
        }
    }
        fclose(input);
        fclose(img);
        return 0;

感谢任何帮助

【问题讨论】:

  • 首先应该切换到二进制模式:使用"rb""wb"而不是"r""w"
  • 您知道,图像可以包含超过 1 个 512 字节的块,是吗?您为每个块打开一个新文件。即使你没有先关闭旧的。
  • 根据咖啡的回答,将} 从第一个if 移到counter++ 行的下方

标签: c cs50 data-recovery


【解决方案1】:

因此,您可以进行此检查以查看您是否找到了新图像的开始。如果你找到一个新图像,你想打开它。但是看看那个分支在哪里结束。您检查它是否是新图像的开始,然后检查是否需要关闭图像。然后你结束两个分支。每次循环运行时,您都会无条件地打开一个新图像。这里唯一的错误是大括号的位置。

//check if file is jpeg
if (file[0] == 0xff && file[1] == 0xd8 && file[2] == 0xff && (file[3] & 0xf0) == 0xe0)
{
    //if a previous file is open, close it
    if (counter != 0)
    fclose(img);
} // <- !! what !!
//initialize new file
sprintf(img_name, "%03i.jpg", counter);
img = fopen(img_name, "w");
counter++;
//if jpeg is found, write

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 2021-05-11
    • 2012-01-30
    • 1970-01-01
    相关资源
    最近更新 更多