首页 > 解决方案 > CS50 - 恢复 - 操作 Card.raw PSET3

问题描述

所以我是一个新手,在 C 中挣扎(真的溺水),试图通过 CS50 工作。我正在进行“恢复”练习,试图从 card.raw 文件中恢复 jpeg。通过谷歌搜索,我了解到通过在终端中输入 xxd -l 2400 card.raw (char is 'L'),我可以在终端中显示 0-2384 字节(含),格式如下:

0000000: 0000 0000 0000 0000 0000 0000 0000 0000 ......

0000950: 0fe0 c11b e555 8f20 33cc fbfe 559e 8eee .....U. 3...你...

Q1:我想使用 printf 显示前 32 个字节(全为 0)(这样我就可以验证正在读取的内容)。我的程序编译,但什么也没显示。(当然,一旦我有这个工作,我会改变它以显示更多字节,因为我知道第一个 jpeg 从哪里开始查看终端中的数据)。

简单的回答表示赞赏(如果我更有经验,我不会发布这样的基本问题)。谢谢,

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

int main()
{

    // hardcode opening of card.raw in read binary mode
    FILE *infile = fopen("card.raw", "rb");

    if (infile == NULL)
    {
        fprintf(stderr, "Could not open infile"); 
        return 2;
    } 

    // declare a variable to hold data to be read from infile file, note that a size for it must be specified
    char text[32];

    /* go to the beginning of the card.raw file to start reading */
    fseek(infile, 0, SEEK_SET);

    // text is the variable that will hold what is read, declared above
    // how many to read, how many to read at a time, where to read from
    fread(text, 32, 1, infile);
    printf("%s\n", text);
}

标签: ccs50recover

解决方案


有几个重大问题。先声明一下char text[32];。回想一下,它char有一个非常具体的含义,它被评估为从 0 到 255 的整数;它是“签名的”。这非常适合阅读 ascii 文本。调用/查看 bmp.hresize以查看应如何声明数据以读取ascii 文本的数据,例如图像数据。

-- 编辑 -- 二进制数据需要是“无符号”数据类型。在 bmp.h 中,作者uint8_t在这里使用typedef uint8_t BYTE;(需要#include stdint.h>)。你可以使用
unsigned char text[32]

其次这个printf("%s\n", text);text被声明为一个字符数组。但是还记得使字符串成为字符串的东西吗?从技术上讲,它是终止的空字节0。因此,当您要求 printf 以text字符串形式打印时,它将打印直到第一个空字节 ( 0) 的所有内容。正如您从十六进制转储中看到的那样,它是文件中的第一个字节。

--edit-- 由于您不能在 printf 中使用字符串格式,您可以一次打印一个字符,就像 mario 或 caesar 一样。但是,由于它是无符号的,格式字符串将%u代替%c. 您可以使用格式字符串%04xx是十六进制的说明符)以十六进制形式查看它。


推荐阅读