gpt4 book ai didi

c - 读取 C 中的 bin 文件未按预期工作

转载 作者:太空宇宙 更新时间:2023-11-04 01:16:01 25 4
gpt4 key购买 nike

嘿,目前我必须为类做一些练习,但我被卡住了。我是 C 的该死的初学者,必须编写一个 vm。

我正在尝试读取 .bin 文件以获取格式、版本、指令数量等信息......

那是我的代码

FILE *inputFile;
char *charBuffer;
int *intBuffer;
long filelen;
char *inputPath = argv[i + 1];
inputFile = fopen(inputPath, "r");
fseek(inputFile, 0, SEEK_END);
filelen = ftell(inputFile);
rewind(inputFile);
charBuffer = (char *)malloc((filelen+1)*sizeof(char));
intBuffer = (int *)malloc((filelen+1)*sizeof(int));

fread(charBuffer, sizeof(char), 4, inputFile);

char *format = charBuffer;
printf("format: %s\n", format);

fread(intBuffer, sizeof(int), 1, inputFile);
int *version = intBuffer;
printf("version: %ls\n", version);

fread(intBuffer, sizeof(int), 1, inputFile);
int *instructionCount = intBuffer;
printf("instruction Count: %ls\n", instructionCount);

fread(intBuffer, sizeof(int), 1, inputFile);
int *variables = intBuffer;
printf("variable Count: %ls\n", variables);

这就是输出:

enter image description here

NJBF 是正确的,但我预计版本为 2。为什么会有这么奇怪的立方体,里面有数字?为什么指令和变量为空?

不幸的是,这门课每周只有一次,我不能请教老师。

这就是用 hexdump 打开的 test1.bin 中的内容

00000000  4e 4a 42 46 02 00 00 00  0b 00 00 00 00 00 00 00  |NJBF............|
00000010 03 00 00 01 04 00 00 01 00 00 00 02 0a 00 00 01 |................|
00000020 06 00 00 01 00 00 00 03 00 00 00 04 00 00 00 08 |................|
00000030 0a 00 00 01 00 00 00 0a 00 00 00 00 |............|
0000003c

规则如下:

  4 bytes        'N', 'J', 'B', 'F' (identifies the format)
4 bytes version number (must match the VM's version number)
4 bytes number of instructions contained in the file
4 bytes number of variables in the static data area
n * 4 bytes instructions (the program to be executed)

最佳答案

版本号是int,不是字符串。您需要使用 %d 格式,并取消引用指针。

printf("version: %d\n", *intBuffer);

在使用%s 打印之前,您还需要向charBuffer 添加一个空终止符。

fread(charBuffer, sizeof(char), 4, inputFile);
charBuffer[4] = 0;
printf("Format: %s\n", charBuffer);

关于c - 读取 C 中的 bin 文件未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58719686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com