c++ - Not able to read whole file -
i'm making c++ program able open .bmp image , being able put in 2d array. right have code this:
#include <iostream> #include <fstream> #include <sstream> #include <string> #include "image.h" using namespace std; struct colour{ int red; int green; int blue; }; image::image(string location){ fstream stream; string tempstr; stringstream strstr; stream.open(location); string completestr; while(!stream.eof()){ getline(stream, tempstr); completestr.append(tempstr); } cout << endl << completestr; image::length = completestr[0x13]*256 + completestr[0x12]; image::width = completestr[0x17]*256 + completestr[0x16]; cout << image::length; cout << image::width; cout << completestr.length(); int hexint; int x = 0x36; while(x < completestr.length()){ strstr << noskipws << completestr[x]; cout << x << ": "; hexint = strstr.get(); cout << hex << hexint << " "; if((x + 1)%3 == 0){ cout << endl; } x++; } }
now if run on test file of 256x256 print fine, until reaches 0x36e gives error / doesn't go further. happens because completestr string doesn't recieve data in bmp file. why isn't able read lines in bmp file?
there number of problems code. principal 1 (and reason problem) opening file in text mode. technically, means if file contains printable characters , few specific control characters (like '\t'), have undefined behavior. in practice, under windows, means sequences of 0x0d, 0x0a converted single '\n'
, , 0x1a interpreted end of file. not 1 wants when reading binary data. should open stream in binary mode (std::ios_base::binary
).
not serious error, shouldn't use fstream
if going read file. in fact, using fstream
should rare: should use either ifstream
or ofstream
. same thing holds stringstream
(but don't see role stringstream
when reading binary file).
also (and real error), using results of getline
without checking whether succeeded. usual idiom reading lines be:
while ( std::getline( source, ling ) ) ...
but stringstream
, don't want use getline
on binary stream; remove of '\n'
(which have been mapped crlf).
if want of data in memory, simplest solution like:
std::ifstream source( location.c_str(), std::ios_base::binary ); if ( !source.is_open() ) { // error handling... } std::vector<char> image( (std::istreambuf_iterator<char>( source ) ), (std::istreambuf_iterator<char>()) );
Comments
Post a Comment