gpt4 book ai didi

CS5Ox Pset4 恢复 : code only recovers partial images

转载 作者:行者123 更新时间:2023-11-30 19:35:12 28 4
gpt4 key购买 nike

我有一些 CS50 Pset4 的半工作代码。如果运行它,您将看到它恢复了 27 个 jpg 文件,但只有前几行可见。

有人能指出我正确的方向吗?

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

typedef uint8_t BYTE;

int main (int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover infile\n");
return 1;
}

// open file to be recovered
FILE *infile = fopen(argv[1], "r");
if (infile == NULL)
{
fprintf(stderr, "Could not open infile.\n");
return 2;
}

// temp storage for blocks
BYTE buffer[512];

// variable to store filename
char filename[8];

//store number of recovered files
int n = 0;

// temp storage for outfiles
FILE* outfile = NULL;

// iterate over all blocks of memory until end of SD card is reached
while (fread(buffer, 512, 1, infile) != 0)
{
// read one block
fread(buffer, 512, 1, infile);

// check if block is start of jpeg
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
//close previous file if already open
if(outfile != NULL)
{
fclose(outfile);
}

// creeate new outfile
sprintf(filename, "%03i.jpg", n);
outfile = fopen(filename, "w");

// write block to outfile
fwrite(buffer, 512, 1, outfile);

n++;
}
else
{
// write block to current outfile
if(outfile != NULL)
{
fwrite(buffer, 512, 1, outfile);
}
}
}

//close last outfile
fclose(outfile);

//close infile
fclose(infile);
}

最佳答案

我发现有几个因素可能会导致该问题。

首先,检查 n 计数器的顺序。应在实际开始写入新文件之前添加计数器,但这只是一个偏好问题以及您希望代码有多干净。

其次,尝试用以下代码替换您的 else 条件:

if(outfile != NULL)                          
{
fwrite(buffer, 512, 1, outfile);
}

注意:请记住,我已将 else 条件替换为 if 条件。这是因为,当满足第一个 if 条件时,它会执行该条件并“跳出 block ”。因此,只有第一个 if 条件不会执行,else 才会执行。如果您想保留 else 条件,那么您应该必须嵌套另一个 if ,就像您在代码中所做的那样。

通过将 else 替换为 if,无论 jpg 的前 3 个字节的值如何(即,无论它们是否0x00、0xff、0x00),您将获得更加清晰易懂的代码。

最后,也是更重要的一点:为什么要在同一个操作中向同一个文件写入两次?请注意 n++ 计数器下方的 fwrite() 函数。真的有必要吗?

换句话说:删除这一行:

//读取一个 block
fread(缓冲区, 512, 1, infile);

另一个错误是,您读取文件两次,并且每一步前进两次,因此您将获得一半的信息。这就是您获得一半图像(大约 27 张)的原因。

删除这两行:

//读取一个 block
fread(缓冲区, 512, 1, infile);

正如我所说,通过在文件中读写两次,您可以获得一半的信息。这导致了一种模糊的方式,在这种方式中,你的图像全部被涂上毫无意义的颜色(我猜)和一半的图像文件。

我已经使用您的代码和我刚刚为您提供的固定解决方案运行了 check50 2016.recover recovery.c,它通过了 CS50 check50 的所有检查。花点时间思考程序中的所有内容,包括控制流(它是程序的重要组成部分)以及指针的使用。

在没有任何经验的情况下开始 CS50 可能会令人畏惧。继续努力吧。您已经快进入第五周了。

关于CS5Ox Pset4 恢复 : code only recovers partial images,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42959301/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com