我正在尝试对CS50的pset4进行“恢复”问题。
尽管我的代码生成了全部50张图片,但是当我运行checkcs50时,还是有一个错误,第一张,中间和049张图片都不匹配。
要清楚,我能够检索000.jpg,然后立即检索文件002.jpg到0050.jpg。
谁能告诉我我在代码中做错了什么吗?提前非常感谢大家!
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
bool magictag(int *);
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr,"Usage:./recover image\n");
return 1;
}
FILE *memorycard = fopen(argv[1], "r");
if (!memorycard)
{
fprintf(stderr, "File cannot be opened\n");
return 2;
}
int file_no = 0;
int b = 0;
char a[1000];
char z[1000];
//While haven't reached EOF
while (((b = fread(a, 512, 1, memorycard) != 0)))
{
//since fread moved the pointer 512 byte forward
fseek(memorycard, -512, SEEK_CUR);
//Check for JPEG Header
uint8_t c[10];
fread(c, 1, 4, memorycard);
fseek(memorycard, -4, SEEK_CUR);
if ((bool) magictag == true)
{
char buffer [50];
sprintf(buffer, "%03i.jpg", file_no);
//Open new JPEG file
FILE *JPEG = fopen(buffer, "w");
if (!JPEG)
{
fprintf(stderr, "jpg cannot be created\n");
return 3;
}
char tmp1[1000];
fread(tmp1, 512, 1, memorycard);
fwrite(tmp1, 512, 1, JPEG);
//copy till a new jpeg is encountered or end of file is reached
int w = 0;
char tmp2[1000];
uint8_t d[10];
while (((w = fread(z, 4, 1, memorycard) != 0)))
{
fseek(memorycard, -4, SEEK_CUR);
fread(d, 4, 1, memorycard);
fseek(memorycard, -4, SEEK_CUR);
if (d[0] == 0xff && d[1] == 0xd8 && d[2] == 0xff && (d[3] & 0xf0) == 0xe0)
{
break;
}
if (d[0] != 0xff || d[1] != 0xd8 || d[2] != 0xff || (d[3] & 0xf0) != 0xe0)
{
fread(tmp2, 512, 1, memorycard);
fwrite(tmp2, 512, 1, JPEG);
}
}
fclose(JPEG);
file_no++;
}
else
{
fseek(memorycard, 512, SEEK_CUR);
}
}
fclose(memorycard);
}
bool magictag(int *c)
{
if (c[0] == 0xff && c[1] == 0xd8 && c[2] == 0xff && (c[3] & 0xf0) != 0xe0)
{
return true;
}
else
{
return false;
}
}