问题
I'm attempting the 'Recover' question on CS50's pset4.
Though my code produced all 50 pictures, there is a bug as when I ran checkcs50, the first, middle, and 049 image doesn't match.
To be clear, I was able to retrieve 000.jpg, followed immediately by files 002.jpg through 0050.jpg.
Can anyone please tell me what I did wrong in my code? Thank you all very much in advance!
Here's my code:
#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;
}
}
来源:https://stackoverflow.com/questions/63453516/my-recovered-images-dont-match-in-cs50-pset4-recover