Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ifstream reading error

I have been trying to read a bmp file with ifstream, however it works fine without debugging, when I run it in debug mode it fails. At the beginning I read 54 bytes of info, to get the height and the width of the picture, which are unfortunately -858993460 in debug mode, so the whole size of my picture overflows everytime, so I get a bad allocation error. I use VS 2013, could anyone help me out with this one ?

unsigned char* readBMP(char* filename)
{

int i;
char info[54];
std::ifstream ifs(filename, std::ifstream::binary);
ifs.read(info, 54);

// extract image height and width from header
int width = *(int*)&info[18];
int height = *(int*)&info[22];

int size = 3 * width * height;

char* data = new char[size]; // allocate 3 bytes per pixel

ifs.read(data, size);
ifs.close();
return (unsigned char*)data;

}
like image 442
blind_mofo Avatar asked Dec 20 '25 14:12

blind_mofo


1 Answers

I guess you failed to open the file, so your read must been failed.

you can check: if (ifs.is_open()) { /* good*/}

you can also check: if(ifs.read(...)){/*good*/}

try this code:

unsigned char* readBMP(char* filename)
{

int i;
char info[54];
std::ifstream ifs(filename, std::ifstream::binary);
if(!ifs.is_open()){ 
   std::cerr<<" failed to open file"<<std::endl;
   return NULL;
 }
if(!ifs.read(info, 54)) {
  std::cerr<<" failed to read from file"<<std::endl;
  return NULL;
} 

// extract image height and width from header
int width = *(int*)&info[18];
int height = *(int*)&info[22];

int size = 3 * width * height;

char* data = new char[size]; // allocate 3 bytes per pixel

ifs.read(data, size);
ifs.close();
return (unsigned char*)data;

}
like image 59
SHR Avatar answered Dec 22 '25 02:12

SHR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!