C ++ STL - 检测到二进制文件的结尾

时间:2011-05-27 11:42:59

标签: c++ file-io std

  

可能重复:
  Why does std::fstream set the EOF bit the way it does?

您好

iam使用read(...)加载二进制文件,然而,eof()永远不会为真 所以我使用gcount()检查文件结束,这显然是完全错误的

如何正确检测二进制文件的eof()?

std::ifstream rf;

rf.open(fpath.c_str(), std::ios::in  | std::ios::binary);

while(!rf.eof()) {

    std::string objectName;

    READ_STR_FROM_BINFILE(rf, objectName);
    //macro code : {
    //  size_t len; 
    //  ff.read(reinterpret_cast<char *>(&len), sizeof(len)); 
    //  std::vector<char> v(len); 
    //  ff.read(&v[0], len); 
    //  ss = std::string(v.begin(), v.end());
    //}

    if (rf.gcount() == 0) {
        //if this happens, there is nothing more to read
        //but the strange thing is, .eof() is not true at this point
        break;
    }

    //loading some structures here

}   

1 个答案:

答案 0 :(得分:2)