首页 > 解决方案 > 我正在用 C 编写一个用于 CS50x Pset 4 Recover 的程序。在我读取第一个块然后尝试编写它之后,我收到一个分段错误

问题描述

CS50X PSet 4 恢复

我读取了第一个数据块并检查它是否是 jpeg 文件的开头。在确定 jpeg 的开头之后,我尝试编写第一个块,这会导致分段错误。

我已将分段错误隔离为将前 512 个字节写入输出文件。

这是一个相关的代码部分

// FILE *file = fopen(argv[1], "r");
FILE* file = NULL;
file = malloc(514 * sizeof(char));
file = fopen(argv[1], "r");
printf("count zero = %d\n", count );

// Check if *file is NULL
if (!file)
{
    printf("count return = %d\n", count );
    return 1;
}

// initialize first_image = 1 for first image
// int first_image=0;

// Read block of 512  bytes
count = fread(bytes, sizeof(char), 512, file);
printf("count = %d\n", count );

while (count != 0)
{
    printf("count 52 = %d\n", count );

    // check if bytes are the jpg header 0xff 0xd8 0xff and oxe? (jpeg)
    if (*bytes[0] == 0xff && *bytes[1] == 0xd8 && *bytes[2] == 0xff && (*bytes[3] & 0xf0) == 0xe0)
    {
        printf("count 56= %d\n", count );

        if (n == 0)
        {
            // create filename
            sprintf(filename, "%03i.jpg", n );
            filename = malloc(9 * sizeof(char));
            // *filename = malloc(9 * sizeof(char));

            // open first file
            fileout = malloc(512 * sizeof(char));
            fileout = fopen(filename,"w");

            // write data to first file
            fwrite(&bytes, sizeof(char), count,

标签: recover

解决方案


推荐阅读