大家好 stackoverflowers。
我正在用 C 代码做一个业余爱好项目,我想在其中对 .BMP 文件进行一些处理。 所以我和我一起使用这个维基百科页面Bmp file format
但很快我就遇到了一个问题。 我正在尝试读取文件的前 14 个字节,即位图文件头。 但是当我打印读取的字节时,它们只有 8 个字节的长度?这是因为其他字节为零还是我做错了什么?
来自 GDB:
(gdb) p pImageHeader
$3 = 0x602250 "BMz\270\v"
(gdb) x pImageHeader
0x600x602250: 0xb87a4d42
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
// If arguments are less than 2, just quit and tell user how do use the god damn program!
if (argc < 2)
{
printf("Usage : %s xxxx.bmp \n", argv[0]);
exit(1);
}
// Create file pointer and attach it to argument file location
FILE* pImageFile;
pImageFile = fopen(argv[1], "r");
// if file doesn't open, quit the program
if (pImageFile == NULL)
{
printf("Some error occured openening file : %s \n", argv[1]);
exit(1);
}
char* pImageHeader;
pImageHeader = malloc(sizeof(char) * 14);
if (pImageHeader == NULL)
{
printf("Error asking for RAM \n");
exit(1);
}
const int HEADER_SIZE = 14;
size_t bytes_read = fread(pImageHeader, 1, HEADER_SIZE, pImageFile);
if (bytes_read < HEADER_SIZE)
{
printf("Something went wrong reading file header! \n");
exit(1);
}
int i = 0;
for (i; i != 14; i++)
{
printf("%02X ", pImageHeader[i]);
}
printf(" \n");
return 0;
}
编辑: 更改源代码以检查实际读取的字节数。它通过了,所以它读取了 14 个字节。
最佳答案
您的代码没问题。你的调试命令不是。
(gdb) p pImageHeader
$3 = 0x602250 "BMz\270\v"
由于 pImageHeader
是一个 char*
,GDB 假定它是一个以 NUL 结尾的“C 字符串”,当您说 p
,它会尝试将其打印出来。如果前 14 个字节中有 NUL
字节,GDB 将停止在那里打印字符。
相反,请尝试 x/14xb pImageHeader
。这将从指针 pImageHeader
打印 14 hex bytes。
当然,您还应该查阅 GDB 的文档,特别是 8.5 Examining memory .
我的 SSCCE :
#include <stdlib.h>
#include <string.h>
int main()
{
char *p = malloc(20);
memcpy(p, "Test\0Worked\0", 12);
return 0;
}
GDB:
(gdb) print p
$1 = 0x601010 "Test" <--- See, this failed!
(gdb) x/12xb p
0x601010: 0x54 0x65 0x73 0x74 0x00 0x57 0x6f 0x72
0x601018: 0x6b 0x65 0x64 0x00
(gdb) x/12cb p
0x601010: 84 'T' 101 'e' 115 's' 116 't' 0 '\000' 87 'W' 111 'o' 114 'r'
0x601018: 107 'k' 101 'e' 100 'd' 0 '\000'
(gdb)
另见:
关于c - 从文件中读取标题部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24353403/