Чтение проблем с двоичными данными

0

Я пытаюсь прочитать битмап файл в C++. Этот файл имеет два заголовка (заголовок файла и заголовок изображения). Мне удалось их прочитать. Но теперь я пытаюсь читать данные, так же, как красные заголовки, я терплю неудачу. Когда я использую метод C для чтения двоичных файлов, все в порядке. Вот коды: im_bmp.cpp

#include <iostream>
#include <fstream>
#include "im_bmp.h"

using namespace std;

void read_bmp(const char* f)
{
   pict I; unsigned char pix[3]; px pxl; int i = 0;

   FILE* fl = fopen(f, "rb");
   fread(&I, sizeof(pict), 1, fl);
   printf("%d\n%d\n",I.im.bpp,I.fhd.f_off); // A test to show the bit per pixel and the offset(where image data begin)

   while(i<2)
   {
       fread(&pix,1,3,fl);
       printf("%d %d %d ",pix[2],pix[1],pix[0]); // A test to show the first two pixels
       i++;
   }

// The code below read binary files in the C++ way
/*
   ifstream ifs;
   ifs.open(f,ios::binary);
   ifs.read((char *)&I,sizeof(pict));
   cout << I.im.bpp << endl;           // It works here. It headers
   ifs.read((char *)&pxl,sizeof(pxl));
   cout << pxl.r << endl;              // It fails here to read the first pixel
*/
   fclose(fl);
}

im_bmp.h

#ifndef IM_BMP_H_INCLUDED
#define IM_BMP_H_INCLUDED

#include <iostream>
#include <fstream>
#pragma pack(1)

using namespace std;
/*
typedef int int32;
typedef short int16;

typedef struct px
{
    unsigned char r, g, b;
} px;

typedef struct pict
{
    int w, h;
    px dt;
} pict;

struct im_hd
{
    int32 hd_sz;
    int32 wdt;
    int32 hgt;
    int16 im_pl;
    int16 bpp;
    int32 cmp;
    int32 im_sz;
    int32 hr;
    int32 vr;
    int32 clr;
    int32 mclr;
};

struct fl_hd
{
    char hd[2];
    int32 sz;
    int32 rsv;
    int32 f_off;
    im_hd im;
};
*/

struct im_hd
{
    int hd_sz;
    int wdt;
    int hgt;
    short im_pl;
    short bpp;
    int cmp;
    int im_sz;
    int hr;
    int vr;
    int clr;
    int mclr;
};

struct fl_hd
{
    char hd[2];
    int sz;
    int rsv;
    int f_off;
    //im_hd im;
};

typedef struct px
{
    unsigned char r, g, b;
} px;

typedef struct pict
{
    fl_hd fhd;
    im_hd im;
    //int w, h;
    //px* dt;
} pict;

void read_bmp(const char* f);

#endif // IM_BMP_H_INCLUDED 

Я пытаюсь сделать это в C++, но это не работает:

   ifstream ifs;
   ifs.open(f,ios::binary);
   ifs.read((char *)&I,sizeof(pict));
   cout << I.im.bpp << endl;           // It works here. It headers
   ifs.read((char *)&pxl,sizeof(pxl));
   cout << pxl.r << endl;              // It fails here to read the first pixel
Теги:
fstream
iostream

1 ответ

1
Лучший ответ

Ваш код C++ работает отлично. Он печатает вам странный символ, потому что cout интерпретирует его как char:

cout << pxl.r << endl; 

Попробуйте применить его как int, чтобы увидеть целочисленное значение:

cout << static_cast<int>(pxl.r) << endl; 

Хотя вы можете обеспечить выравнивание структуры с помощью #pragma pack, может быть безопаснее прочитать пиксель, не учитывая размер структуры:

ifs.read((char *)&pxl.r, sizeof (unsigned char));
ifs.read((char *)&pxl.g, sizeof (unsigned char));
ifs.read((char *)&pxl.b, sizeof (unsigned char));
  • 2
    Отличный пример того, почему «Здесь не получается» не является достаточным описанием проблемы.
  • 0
    Спасибо, Закинстер, это была именно моя проблема, и ты решил ее.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню