首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

C++二进制文件读写有关问题

2012-04-06 
C++二进制文件读写问题在遍历二进制文件的时候,总是在正确执行一定的二进制读取之后,v.fail()就会变成ture

C++二进制文件读写问题
在遍历二进制文件的时候,总是在正确执行一定的二进制读取之后,v.fail()就会变成ture

C/C++ code
void readType(std::ifstream &v, T *foo) {    if(!v.good())        std::cout<< "Attention! Ifstream is not good"<< std::endl;    else         std::cout<< "Attention! Ifstream is  good"<< std::endl;    //v.read((char *)foo, sizeof(T));    v.readsome((char *)foo, sizeof(T));    std::cout<<v.gcount()<<"    bit has been read"<<endl;    if(v.eof()) std::cout<< "ERROR: EOF" <<std::endl;    if(v.bad()) std::cout<<"ERROR: badbit" <<std::endl;    if(v.fail()) std::cout<<"ERROR: failbit" <<std::endl;}for (int i = 0; i < NumDOFS; ++i) {    char len;                        readType(v, &len);    char * buffer_DOFlabel = new char[len];    v.read(buffer_DOFlabel, len);    DOFlabels.push_back(string(buffer_DOFlabel));    delete [] buffer_DOFlabel;}


输出结果为:
Attention! Ifstream is good
1 bit has been read
DOFlabel 23's length: 23
DOFlabel 23's contents: khairi:RightFoot <t-Z>
Attention! Ifstream is good
0 bit has been read
DOFlabel 24's length: 26
DOFlabel 24's contents: 屯屯屯屯屯屯屯屯屯屯屯屯屯铪铪铪铪铪
Attention! Ifstream is not good
0 bit has been read

第23此执行能够正确执行,得到的内容是khairi:RightFoot <t-Z>,第24次执行就出现错误。请问这个是由什么引起的?有什么调试方法吗?


[解决办法]
readsome()造成的。
看MSDN解释:Read from buffer only. 
Remarks
The unformatted input function extracts up to count elements and stores them in the array beginning at _Str. If good is false, the function calls setstate(failbit). Otherwise, it assigns the value of rdbuf->in_avail to N. If N < 0, the function calls setstate(eofbit). Otherwise, it replaces the value stored in N with the smaller of _Count and N, and then calls read(_Str, N). In any case, the function returns gcount. 

如果N == 0时(即buffer为NULL),就会造成了上面的结果

[解决办法]
//char * buffer_DOFlabel = new char[len]; 改为
char * buffer_DOFlabel = new char[len+1];

试试。

热点排行