Вопрос

I am trying to read the FILEHEADER and INFOHEADER of a bitmap file, but I am unable to do so. I am getting Segmentation Fault.

My code has been given below.

#include <bits/stdc++.h>

using namespace std;

typedef int LONG;
typedef unsigned short WORD;
typedef unsigned int DWORD;

struct BITMAPFILEHEADER {
  WORD  bfType;
  DWORD bfSize;
  WORD  bfReserved1;
  WORD  bfReserved2;
  DWORD bfOffBits;
};

struct BITMAPINFOHEADER {
  DWORD biSize;
  LONG  biWidth;
  LONG  biHeight;
  WORD  biPlanes;
  WORD  biBitCount;
  DWORD biCompression;
  DWORD biSizeImage;
  LONG  biXPelsPerMeter;
  LONG  biYPelsPerMeter;
  DWORD biClrUsed;
  DWORD biClrImportant;
};

int main(void){
    ifstream file("lena.bmp");
    char* bf = NULL;
    int begin = file.tellg();
    file.seekg(0, ios::end);
    int end = file.tellg();
    int length = end-begin;

    file.read(bf, length);
    BITMAPFILEHEADER* file_header = (BITMAPFILEHEADER*)(bf);
    //BITMAPINFOHEADER* info_header = (BITMAPINFOHEADER*)(bf+sizeof(BITMAPFILEHEADER)-1);

    cout << file_header->bfSize << endl;
    //cout << info_header->biSize << endl;
    return 0;
}
Это было полезно?

Решение

The segmentation fault is probably because you forgot to initialize bf;

int end = file.tellg();
int length = end-begin;
bf = new char[lenght+1]; //Add this
file.seekg(0, ios::beg); //And this too
file.read(bf, length);

[EDIT]

The second problem (size is always 0) occurs because the file pointer is at the end of the file, so you never read anything actually.

Другие советы

As was mentioned in the previous reply, you where trying to file.read with a null pointer. I see that you are trying to load the whole file into memory, then do some pointer arithmetics to work with the data. But why not just read the BITMAPFILEHEADER directly instead?

ifstream file("lena.bmp");

// read in the header:
BITMAPFILEHEADER header;
file.read(reinterpret_cast<char *>(&header), sizeof(header));

// validate the header, get the size in bytes of the bitmap data
size_t bitmapSizeBytes = width * height * channels; // or something like that...

// Now read the bitmap. Use a vector to simplify memory management:
std::vector<unsigned char> bitmap;
bitmap.resize(bitmapSizeBytes);

file.read(reinterpret_cast<char *>(&bitmap[0]), bitmapSizeBytes);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top