我正在进行CS50恢复,但我无法让程序检查JPEG起始标题。
我使用了debug50并添加了几个打印语句来尝试查找问题。每次运行该程序时,它都会打印出"No Output File2“,这意味着不会创建输出文件,并且会跳过IsJPEG布尔检查。
在进一步调试时,缓冲区似乎一直是0'\000\,所以我怀疑缓冲区中没有写入任何内容,导致程序跳过布尔检查(触发fopen),从而导致它中断。
然而,我很难找到什么都没有写入buffer的原因。
请帮忙,谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <stdint.h>
typedef uint8_t BYTE;
bool isJPEG(BYTE buffer[]);
int main(int argc, char *argv[])
{
    BYTE buffer[512];
    int fileCounter = 0;
    char filename[8];
    if (argc != 2)
    {
        printf("%s\n", "Usage: ./recovery file");
        return 1;
    }
    FILE* infile = fopen(argv[1], "r");
    if (infile == NULL)
    {
        printf("%s\n", "Error: File Not Found");
        return 1;
    }
    FILE* outfile;
    while (fread(buffer, 512, 1, infile))
    {
        if (isJPEG(buffer))
        {
            if (fileCounter == 0)
            {
                sprintf(filename, "%03i.jpg", fileCounter++);
                outfile = fopen(filename, "w");
                printf("%s\n", "Bool 1");
            }
            else
            {
                fclose(outfile);
                sprintf(filename, "%03i.jpg", fileCounter++);
                outfile = fopen(filename, "w");
                printf("%s\n", "Bool 2");
            }
            if (outfile == NULL)
            {
                printf("%s\n", "No Output File 1");
                return 1;
            }
            fwrite(buffer, 512, 1, outfile);
        }
        else
        {
            if (outfile == NULL)
            {
                printf("%s\n", "No Output File 2");
                return 1;
            }
            fwrite(buffer, 512, 1, outfile);
        }
    }
    fclose(outfile);
    fclose(infile);
}
bool isJPEG(BYTE buffer[])
{
    return buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0;
}发布于 2021-06-07 02:23:13
它打印"No output file2“,因为它被告知要这样做。当脚本第一次运行时,执行会进入if (isJPEG(buffer))的else语句,在该语句中,它会检查outfile是否为NULL。它确实是NULL,因为它没有指向任何内容,并且打印了No output file 2。相反,应该检查outfile是否指向一个文件,只有这样我们才应该在它上面写东西。我将脚本改正如下;
 while (fread(buffer, 512, 1, infile))
    {
        if (isJPEG(buffer))
        {
            if (fileCounter == 0)
            {
                sprintf(filename, "%03i.jpg", fileCounter++);
                outfile = fopen(filename, "w");
                printf("%s\n", "Bool 1");
            }
            else
            {
                fclose(outfile);
                sprintf(filename, "%03i.jpg", fileCounter++);
                outfile = fopen(filename, "w");
                printf("%s\n", "Bool 2");
            }
            if (outfile != NULL)
            {
                fwrite(buffer, 512, 1, outfile);
            }
        }
        else
        {
            if (outfile != NULL)
            {
                fwrite(buffer, 512, 1, outfile);
            }
        }
    }https://stackoverflow.com/questions/67809570
复制相似问题