恢复cs50:它恢复了000.0jpg,但当我再次运行它时,没有用check50进行任何更改.它不起作用


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

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

FILE *file = fopen(argv[1],"r");
if (file == NULL)
{
printf("This file cannot be opened.n");
return 1;
}

//512B is the size of 1 block
unsigned char buffer[512];
FILE *img = NULL;

//we alr know that there is 50 images for us to recover
string filename[50];
int count = 0;

// read 1 element of 512B into buffer array
while (fread(buffer, sizeof(unsigned char), 512, file) == 512 *sizeof(unsigned char))
{
//NEW jpeg
if (img == NULL)
{
//start of jpeg
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
//create filename(string not array) for new file
sprintf(filename[count], "%03i.jpg", count);

//create new jpeg file with new filename & write/append in card.raw
img = fopen(filename[count],"w");
fwrite(buffer, 512, 1, img);
fclose(img);
}
//continue while loop and read file if cannot find jpeg signature
}
else
{
//Discover jpeg signature
//End of jpeg + Start of new jpeg
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
fclose(img);
//intialize pointer
img = NULL;
count++;

//create filename(string not array) for new file
sprintf(filename[count], "%03i.jpg", count);

//create new jpeg file with new filename & write/append in card.raw
img = fopen(filename[count],"w");
fwrite(buffer, 512, 1, img);
}
else
{
//continue writing to jpeg file
fwrite(buffer, 512, 1, img);
}
}
}

if (!feof(file))
{
printf("Unknown error occuredn");
return 1;
}

printf("%i jpeg images recoveredn", count);
fclose(file);
return 0;
}

未定义行为消毒器:DEADLYSIGNAL该信号是由写入内存访问引起的提示:地址指向零页面

怎么了?我好像想不通。这是一个逻辑问题吗?它恢复了000.0jpg,但当我再次运行它时,没有用check50做任何更改(至少我认为我没有做任何更改(。它不起作用??

问题是:如果将由get_string填充,则只应使用string数据类型。我认为课程材料中没有明确提到,但由于内存分配的原因,否则就不起作用了。由于filename的50个元素没有得到正确的分配,将出现不可预测的结果。

考虑一下:filename是否需要是一个字符串数组?有什么理由";保持";所有的文件名?每个都将只使用一次,不再需要。如果filename字符的数组,那么它就足够了。它必须用足够的字节来声明,以容纳文件名和终止的null字节。

虽然这个//we alr know that there is 50 images for us to recover对于发行版代码中包含的原始文件是正确的,但它是不必要的限制。如果分级程序使用的原始文件只包含10张照片,或者包含100张照片,该怎么办?

最新更新