c++ std::ifstream 读取文件不完整? 是不是忘记了ios_base::binary

来源:互联网 发布:浙江纺织品出口数据 编辑:程序博客网 时间:2024/06/06 00:29

一次浪费时间又把你折磨的无以复加的小问题。

读取图片本应该读取20000字节的,为何只读取了300字节?原来少了ios_base::binary!!!

如果读取的非字符串形式的文本,注意应该要加上ios_base::binary,否则可能遇到0就提前返回了EOF。

下面直接上我出过问题的代码,当然现在是正确的...

//发送图片的图片数据缓冲区boost::shared_ptr<char> _img_buffer;unsigned int _img_buffer_size;

{#define IMG_RES "../Debug/767011.jpg"using namespace std;std::ifstream* tmpImg = new std::ifstream(IMG_RES, ios_base::in | ios_base::_Nocreate | ios_base::binary);if(tmpImg == NULL || !tmpImg->is_open()){ASSERT_THROW;}tmpImg->seekg(0, ios::end);_img_buffer_size = (int)tmpImg->tellg();if(_img_buffer_size == -1){ASSERT_THROW;}if(_img_buffer != NULL){ASSERT_THROW;}_img_buffer = boost::shared_ptr<char>(new char[_img_buffer_size], [](char* p){delete [] p; p=NULL;});if(_img_buffer == NULL){ASSERT_THROW;}memset(_img_buffer.get(), 0, _img_buffer_size);tmpImg->seekg(0, ios::beg);unsigned int tmpCount = 0;do {std::istream& tmpIs = tmpImg->read(_img_buffer.get()+tmpCount, _img_buffer_size-tmpCount);if(tmpIs.eof()){break;}if(tmpIs.rdstate() != std::ios_base::goodbit){ASSERT_THROW;}tmpCount += (unsigned int)tmpIs.gcount();} while (tmpCount < _img_buffer_size);tmpImg->close();SAFE_DELETE(tmpImg);}


0 0
原创粉丝点击