Reading bitmap header

I'm trying to read a bitmap header and according to the specifications I have done it correctly. The section of the header that contains the size of the bitmap file has an offset of 2 bytes and is 4 bytes long, however whenever I run this program it states the size is "6". The actual size of the bitmap is 192kb.

Are there any decent tutorials to reading bitmaps (cross-platform, so no Win32 LoadBitmap() function)? I've googled but had no luck.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cstdlib>
#include <cstdio>
#include <iostream>

using namespace std;

int main(int argc, char** argv) {
    FILE * file;
    file = fopen("texture.bmp", "rb");
    unsigned char * size;     
    fseek(file, 2, SEEK_SET);  
    if(fread(size, 4, 1, file)  != 0)
    {                                
        cout << "Successful read";   
    }
    fclose(file);                    
    cout << size;
    return 0;
}


EDIT: oo, I just spotted I'm checking if fread() returns anything but zero then it's successful which is wrong. Changed to:

 
if(fread(size, 4, 1, file)  == 0)


which means the file isn't reading and I don't have a clue why.
Last edited on
size is uninitialized.
check the documentation
elements_read fread( storage_pointer, size_of_element, number_of_elements, stream);
Thanks for the tip, I'll have a look now.
removed
Last edited on
Actually it will be much easier for you to get some Open Source C/C++ libraries that can manipulate BMP files.

Google to see if there is already BMP processing libraries out there. Don't re-invent the wheel :)
But this is something that should be simple! How hard can it be to read 4 bytes from the start of a file with an offset of 2 bytes?

I've managed to read the first 2 bytes which are the 'magic number' used to identify the type of BMP file, but that's it. :(

This for example, works perfectly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <cstdlib>
#include <cstdio>
#include <iostream>

using namespace std;

int main(int argc, char** argv) {
    FILE * file;
    file = fopen("texture.bmp", "rb");
    unsigned char * magicNumber;
    fread(magicNumber, 2, 1, file);
    fclose(file);                    
    cout << magicNumber;
    return 0;
}
Last edited on
fread( size, sizeof(char), 4, file); size is already a pointer. I don't know what will happen if you lie in the size of the cell (maybe endianness issues).
You could also try to use std::fstream
Alrighty, I'll try fstream.
Topic archived. No new replies allowed.