如果条件未执行(cs50恢复)

问题描述 投票:0回答:1

我已经尝试寻找该错误几个小时了。写入分段错误。请帮忙;)

任务页面:https://cs50.harvard.edu/x/2024/psets/4/recover

任务是恢复从存储卡中删除的 50 个 JPEG 文件。我们被指示检查 fread 的每个 512 字节通道的前 4 个字节,以指示 JPEG 文件的开始并将其写入新文件。一旦达到另一个匹配的 4 个字节,我们就应该关闭前一个文件并写入一个新文件,直到达到 EOF(存储卡中的数据在名为 card.raw 的文件中提供给我们)。

在我的决定中, if (buffer[0] == 0xff 等不执行, while 立即出现 else ,因为据我所知,写入了分段(核心转储)错误。

即代码被编译,执行后显示如下: 执行时 否则执行 分段错误(核心转储)

但是条件本身写的是正确的,因为我把它改成了别人写的。看起来卡上的数据没有写入缓冲区。

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>

#define BLOCK_SIZE 512
typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    // Accept a single command-line argument
    if (argc != 2)
    {
        printf("Usage: ./recover FILE\n");
        return 1;
    }

    // Open the memory card
    FILE *card = fopen(argv[1], "r");

    if (card == NULL)
    {
        printf("Could not open file.\n");
        return 1;
    }

    BYTE buffer[BLOCK_SIZE];
    int number_file = 0;
    char filename[8];
    FILE *img = NULL;
    bool this_first_jpeg = true;

    // While there's still data left to read from the memory card
    while(fread(buffer, BLOCK_SIZE, 1, card) == 1)
    {
        printf("while executed\n");
        // if start of new JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] >= 0xe0 && buffer[3] <= 0xef))
        {
            printf("if executed\n");
            if (this_first_jpeg == true)
            {
                sprintf(filename, "%03i.jpg", number_file++);
                img = fopen(filename, "w");
                fwrite(buffer, BLOCK_SIZE, 1, img);
                this_first_jpeg = false;
            }
            else
            {
                fclose(img);
                sprintf(filename, "%03i.jpg", number_file++);
                img = fopen(filename, "w");
                fwrite(buffer, BLOCK_SIZE, 1, img);
            }
        }

        // if already found JPEG
        else
        {
            printf("else executed\n");
            fwrite(buffer, 1, BLOCK_SIZE, img);
        }
    }

    fclose(card);
    fclose(img);

    return 0;
}

我尝试获取其他人的代码,但仍然不起作用。但其他代码完全可以工作。

c cs50
1个回答
0
投票

请注意以下备注:

  • 您应该以二进制模式打开文件:

    FILE *card = fopen(argv[1], "rb");

  • 图像文件相同:

    img = fopen(filename, "wb");

© www.soinside.com 2019 - 2024. All rights reserved.