简体   繁体   English

用fread()读取BMP的文件头

[英]Reading Fileheader of a BMP with fread()

I am working on Linux trying to load the header of a BMP. 我正在Linux上尝试加载BMP的标头。 I've looked at the header and should be getting "BM" for the first two characters of the file. 我看过标题,并且文件的前两个字符应该为“ BM”。 The code I've been using: 我一直在使用的代码:

FILE* fp = fopen(filename, "r");
if(!fp)
{
    std::cout << "Unable to open file : " << filename << std::endl;
    return NULL;
}

char* headerField = new char[2];
fread(headerField, 2, sizeof(char), fp);
std::cout << headerField << std::endl;

if(strcmp(headerField, "BM")){
    delete [] headerField;
    std::cout << "File is not a bitmap" << std::endl;
    fclose(fp);
    return NULL;
}
else{
    std::cout << "Well done!" << std::endl;
}

The output I'm getting is BM followed by a random extra character, "BM7", "BMF", "BM*"... As I understand it, fread() should read in (in this case) two characters worth of data, so where is this extra character coming from? 我得到的输出是BM,后跟一个随机的额外字符“ BM7”,“ BMF”,“ BM *” ...据我所知,在这种情况下,fread()应该读入两个字符数据,那么这个额外的字符从哪里来?

You are heavily mixing c and c++, I think this is half of the reason why you got into the bug in the 1st place. 您正在大量混合使用c和c ++,我认为这是您首先进入bug的一半原因。

Now, in c strings are called null-terminated strings of characters for a reason. 现在,由于某种原因,在c字符串中称为以null终止的字符串。 The null character \\0 is an end of string delimiter. 空字符\\0是字符串定界符的结尾。 What you are doing is reading two bytes into the headerField . 您正在做的是将两个字节读取到headerField So in memory it looks like: 因此在内存中看起来像:

| | B | B | M | M | garbage | 垃圾| garbage | 垃圾| garbage | 垃圾|

str family, and other routines expect the char* strings to have \\0 at the end. str家族和其他例程希望char*字符串的末尾有\\0 So the strcmp , and printing does not stop after M but run into the wild. 因此, strcmp和打印不会在M之后停止,而是会陷入困境。 A proper 2 character c-style string should occupy 3 bytes and look like: 正确的2个字符的c样式字符串应占用3个字节,如下所示:

| | B | B | M | M | 0 | 0 | garbage | 垃圾| garbage | 垃圾|

How you make it happen I leave up to you. 你如何做到的,我取决于你。

I would rewrite the code into a proper c++ personally. 我会亲自将代码重写为适当的c ++。

The "extra garbage" is already there in memory. 内存中已经有“额外的垃圾”。

fread() does exactly what you tell it. fread()完全按照您所说的进行。 It reads 2 chars. 它读取2个字符。 C and C++ use null terminated char strings. C和C ++使用以null终止的char字符串。 cout is going to print whatever is in the buffer until it reaches a null terminator. cout将打印缓冲区中的所有内容,直到到达空终止符为止。

You should create a string longer than 2, and you should set a null char. 您应该创建一个长于2的字符串,并应设置一个空字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM