c - 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);
}
解决方案
有几个重大问题。先声明一下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
. 您可以使用格式字符串%04x
(x
是十六进制的说明符)以十六进制形式查看它。
推荐阅读
- node.js - 维护两个不同应用程序所需的服务
- xcode - 如何在 Xcode 中将库与 rpath 链接?
- python - 使用 openpyxl 加载工作簿时的进度条
- javascript - 如何制作一个 js 代码,仅当用户满足“if”条件时才允许用户查看他们的页面?
- php - 无法将任何样式表添加到 prestashop 1.7 中的模块
- javascript - 现在服务中的这段代码是什么意思?
- python - 具有字符串格式的python正则表达式模式
- javascript - 点击提交按钮后输入文本区域的文本
- python - 如何摆脱 CSV 中的撇号但保持前导 0?
- arrays - 将嵌套结构中的数组附加到另一个嵌套结构中的另一个数组