我有一个关于如何恢复 jpg 图像的问题(这是 CS50 的作业)。我的代码大部分都有效(我相信),但是当我打开找到的 jpg 时,我只会得到一堆缩略图。
我已经尝试解决这个练习很长一段时间了,但我似乎无法弄清楚为什么它不起作用。有人可以帮我推动正确的方向。
这是我的代码(也可在http://pastebin.com/U2pwJd5e获得):
#include <stdio.h>
#include <stdlib.h>
#include "bmp.h"
int main(int argc, char* argv[])
{
//get input file
char* infile = "card.raw";
// open card file
FILE* inptr;
inptr = fopen("card.raw", "r");
// error checking (copied from copy.c)
if (inptr == NULL)
{
printf("Could not open %s.\n", infile);
return 2;
}
// initialize buffer
BYTE buffer[512];
//initialize jpg variables:
int increment = 0;
char outfilename[8];
// while the end of the file is not reached, continue process & write to buffer next block of 512 bytes
while (fread(buffer, 512, 1, inptr) != 0)
{
// if the inpointer is not empty
if(inptr != NULL)
{
// If the block of 512 bytes starts with markers
if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3]== 0xe1 || buffer[3]== 0xe0))
{
// increase file number by 1
sprintf(outfilename,"%.3d.jpg", ++increment);
// open new file
FILE* outptr;
outptr = fopen(outfilename, "a");
// write first block of 512 bytes, then read next block
fwrite(buffer, 512, 1, outptr);
if(fread(buffer, 512, 1, inptr) == 0)
break;
// copy all information from inpointer to buffer to jpg
while((buffer[0] != 0xff && buffer[1] != 0xd8 && buffer[2] != 0xff && (buffer[3]!= 0xe1 || buffer[3]!= 0xe0) ))
{
// if next byte is NULL break
if(fread(buffer, 512, 1, inptr) == 0)
break;
fread(buffer, 512, 1, inptr);
//copies jpg file 1 byte at a time
fwrite(buffer, 512, 1, outptr);
}
// close file
fclose(outptr);
}
}
}
return 0;
}