首页 > 解决方案 > CS50 RECOVER 寻找迭代条件语句

问题描述

大家好,这是一个CS50作业,它假设通过C的文件处理功能从存储卡中恢复一堆照片。它恢复了第一张照片(即000.jpeg)但是当涉及到继续新的jpeg时它只能写一个块(512BYTE)一次然后停止。我正在寻找一个条件让它自动化(参考上面的 printf("I can write to the new jpeg\n");) 与 while 循环但 isjpeg() 函数不可操作,因为它具有相同的开头(不知道为什么,但尝试不起作用)。我正在寻找一种延续它的方式。感谢所有帮助赞赏。

(这是终端上的输出,以便您看到结果,为了便于演示,减少了 I could not found new 的数量。)

$ ./recover card.raw
I could not found a new so keep goin
I could not found a new so keep goin
I can found the first jpeg
I could not found a new so keep goin
I could not found a new so keep goin
I could not found a new so keep goin
I could not found a new so keep goin
I could not found a new so keep goin
I could not found a new so keep goin
I can write to the new jpeg

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef unsigned char BYTE;
int main(int argc, char *argv[])
{
    int jpegnumber; jpegnumber = 0;
    bool isjpeg();
    bool jpeghasfound = false;
    char filename[8];

    if (argc != 2 )
    {
        printf("Program should have one command line argument \n");
        return 1;
    }

    FILE *file = fopen(argv[1], "r");

    if (file == NULL)
        return 1;

    BYTE buffer[512];

    FILE* img;

    while (fread(buffer, 512, 1, file)) // if it reads something
    {
        if ( isjpeg(buffer) && (!jpeghasfound) ) // it founds a jpeg first time
        {
            jpeghasfound = true;

            sprintf(filename,"%03i.jpg",jpegnumber);

            img = fopen(filename,"w");
            printf("I can found the first jpeg\n\n");
            if (img == NULL)//nullcheck
            {
                printf("There is nothing to open \n");
                return 1;
            }
            fwrite(buffer,512,1,img);

            jpegnumber++; // increment the count
        }

        else if (isjpeg(buffer) && jpeghasfound)  // Founding a new jpeg
            {
                fclose(file); // close old file
                sprintf(filename,"%03i.jpg",jpegnumber);
                if (img == NULL)//nullcheck
                {
                    printf("There is nothing to open \n");
                    return 1;
                }
                    fwrite(buffer,512,1,img);
                    printf("I can write to the new jpeg\n");
            }
        else  // if we have not find a new jpeg we should keep writing to old file
        {
            fwrite(buffer,512,1,img);
            printf("I could not found a new so keep goin\n");
        }

    }
    fclose(file);
    fclose(img);
}

bool isjpeg(BYTE buffer[])
{

        if((buffer[0] == 0xff ) && (buffer[1] == 0xd8 ) && (buffer[2] == 0xff ) && ((buffer[3] & 0xf0 ) == 0xe0))
        {
            return true;
        }
        else
        {
            return false;
        }
}

标签: ccs50recover

解决方案


推荐阅读