解析位图的字节 header 并使用文件指针保存

Parsing bytes of a bitmap header and saving with file pointers

我正在处理我的第一个 C 编程 class 中的第一个项目,但我迷失了方向。我们将以各种方式改变位图,我很难理解如何使用文件指针来获取我想要使用和操作的字节数据。我知道位图文件 header 和 DIB header 结构以及构成它们的值的字节偏移量。但是,我很难理解如何保存这些值中的每一个以供以后与文件指针一起使用。由于这是一个项目,我不想寻求太多帮助。到目前为止,这是我的代码,我试图通过各种方式捕获 header:

的部分内容
int main(int argc, const char * argv[]){
    FILE *fp;
    char buff[2]; //only trying '2' to try and capture 'BM' at start of file.
    fp = fopen(argv[1], "r+b");
    fseek(fp, 0, SEEK_END);
    long fsize = ftell(fp);
    rewind(fp);

    // this is where I test what to do but can't get it correct
    unsigned short filetype = fgetc(fp);
    printf("First letter of filetype %c\n", filetype); //prints 'B' which is awesome

    //Now I do not understand how to capture both the 'BM'.
    //I've changed to use the fread as follows:
    fread(buff, sizeof(char), 2, fp);
    printf("Captured bytes with fread %s\n", buff) //this prints 4 char's and not 2? 

    fclose(fp);
    return 0;
}

我还测试了一个简单的 while 循环来遍历整个文件并打印每个字符,直到使用 fgetc 遇到 EOF 为止。所以我假设每次调用 fgetc 都会将指针当前字节位置的位置更改为当前位置 + 1.

我想我没有完全理解如何使用文件指针将大量字节保存到单个存储变量中。我也试过 fseekfgets 无济于事。

我很感激能从这里的社区获得任何帮助和意见。

printf("%s", buff) 打印 buff 指向的字符和后续字符,直到它到达 NUL 字符。不幸的是,buff 只包含 BM,因此 printf 一直读取数组末尾,直到找到 NUL。太糟糕了!

替换

char buff[2];
fread(buff, sizeof(char), 2, fp);

char buff[3];
size_t num_read = fread(buff, sizeof(char), 3, fp);
buff[num_read] = 0;

请注意,sizeof(char) 保证为 1

请注意,fgetc 将文件指针推进到 B 之外,因此如果您希望 fread 读取 B,则需要再次倒回它].