CS50从card.raw恢复jpg图像

时间:2018-02-12 05:01:14

标签: c image jpeg cs50 recovery

我有一些关于CS50 Pset4恢复jpg文件问题的问题。 我的代码能够编译,但是只创建了2个jpg文件,即使它应该创建了50个jpg文件。我没有看到代码有任何问题,但我怀疑jpg文件没有被创建,因为fread函数以某种方式早于它应该到达EOF。但我对此毫无头绪。任何帮助识别错误的人都会非常感激:D

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

int main (int argc, char * argv[])
{
//Only accepts 2 arguements
if (argc != 2)
{
    fprintf(stderr, "Usage: Recover JPEG images\n");
    return 1;
}

//opens file file for reading
FILE *file = fopen(argv[1], "r");
if (file == NULL)
{
    fprintf(stderr, "Unable to open file\n");
    return 2;
}

unsigned char buffer[512];

//initializing file numbering
int count = 0;
char filename[7];
FILE *img = NULL;

//reads 512 bytes each time until EOF
while(fread(buffer, 512, 1, file) == 1)
{
    //Detect the start of a JPEG file
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
    {
        //if output file was not created before, create one
        if (img == NULL)
        {
            sprintf(filename, "%03i.jpg", count);
            img = fopen(filename, "w");

            if (img == NULL)
            {
                fprintf(stderr, "Unable to open %s\n", filename);
            }

            fwrite(buffer, 512, 1, img);
            count += 1;
        }
        //if output file was already created, close it and open a following output file
        else
        {
            fclose(img);

            sprintf(filename, "%03i.jpg", count);
            img = fopen(filename, "w");

            if (img == NULL)
            {
                fprintf(stderr, "Unable to open %s\n", filename);
            }

            fwrite(buffer, 512, 1, img);
            count += 1;
        }
    }
    //if there is an output file open but has not reached the start of a new jpg, write into the current opened file
    else
    {
         if (img != NULL)
         {
             fwrite(buffer, 512, 1, img);
         }
    }
}
//close all files
if (img)
{
    fclose(img);
}
fclose(file);

2 个答案:

答案 0 :(得分:0)

fread使文件指针前进:

while(fread(buffer, 512, 1, file) == 512)
{
    fread(buffer, 512, 1, file);

此执行实际读取1024字节但缓冲区仅保留下半部分(512字节),这意味着每个循环将跳过512字节

--------------------------
|512b|512b|512b|512b|512b|
--------------------------
-skip-read-skip-read-skip-

是故意的吗?

答案 1 :(得分:0)

好的,我终于找到了问题所在。问题是我分配了char filename[7];,其中我给出了数字7,因为每个文件的名称都是00x.jpg我相信使用7个字符。然而,似乎该程序仅在我输入高于7的数字时才有效,例如'8'或'10'。我相信这个额外的字符空间用于'\ 0'我没有考虑到。如我错了请纠正我。感谢所有帮助过的人:D