我正在尝试对CS50的pset4进行'恢复'问题。
看来,我能够检索除001.jpg以外的所有图像。考虑到check50告诉我以下内容,我怀疑这会进一步导致文件编号不一致:-
:)正确恢复000.jpg
:(可以正确恢复中间图像 找不到001.jpg
:(可正确恢复049.jpg 恢复的图像不匹配
[要清楚,我能够检索000.jpg,然后立即检索文件002.jpg到0050.jpg。跟踪jpeg文件数的计数器似乎正在运行,因此我很困惑为什么可能会跳过001。
[如果有人可以帮助我确定我的代码是否存在逻辑错误,将不胜感激。我有一种预感,当程序立即跳转到“ else”分支(其中前4个字节不是JPEG标头)时,会出现一些问题?提前非常感谢大家!
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
//Check for 1 command line argument
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
//Opening forensic image file & getting its file pointer called "raw"
FILE *raw = fopen(argv[1], "r");
if (raw == NULL) //Checking if pointer returns a null value
{
return 1;
}
//Create counter to keep track of no. of JPEG files
int counter = 0;
//Creating a buffer with a size of 512 x BYTES
BYTE buffer[512];
//Creating a string for file name
char filename[8];
while (fread(buffer, sizeof(BYTE), 512, raw) == 512)
{
//Checking if first 4 bytes are JPEG headers
if (buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff &&
(buffer[3] & 0xf0) == 0xe0)
{
//If it is first JPEG file
if (counter == 0)
{
//Determine file name
sprintf(filename, "%03i.jpg", counter);
//Open new file
FILE *output = fopen(filename, "w");
//Write to new file
fwrite(buffer, sizeof(BYTE), 512, output);
//Increment JPEG file count by 1
counter++;
//Close file
fclose(output);
}
else //if not first JPEG file (i.e. counter !=0)
{
//Increment JPEG count first so that file name will be +1 as well
counter++;
//Determine next file name
sprintf(filename, "%03i.jpg", counter);
//Open new file
FILE *output = fopen(filename, "w");
//Write to new file
fwrite(buffer, sizeof(BYTE), 512, output);
//Close file
fclose(output);
}
}
else //if first 4 bytes are not JPEG headers
{
//Open previous file (because there is no count increment)
FILE *output = fopen(filename, "a"); //used 'a' instead to amend instead of
overwriting previous file with 'w'
//Write to previous file
fwrite(buffer, sizeof(BYTE), 512, output);
//close file
fclose(output);
}
//For checking - to remove later
printf("%i\n", counter);
}
fclose(raw);
return 0;
}
FILE *output = fopen(filename, "a"); //used 'a' instead to amend instead of
overwriting previous file with 'w'
filename
未初始化。