c++ file bad bit

被刻印的时光 ゝ 提交于 2020-01-15 07:59:27

问题


when I run this code, the open and seekg and tellg operation all success. but when I read it, it fails, the eof,bad,fail bit are 0 1 1.

What can cause a file bad? thanks


int readriblock(int blockid, char* buffer)
{
   ifstream rifile("./ri/reverseindex.bin", ios::in|ios::binary);

   rifile.seekg(blockid * RI_BLOCK_SIZE, ios::beg);
   if(!rifile.good()){ cout<<"block not exsit"<<endl; return -1;}
   cout<<rifile.tellg()<<endl;

   rifile.read(buffer, RI_BLOCK_SIZE);

   **cout<<rifile.eof()<<rifile.bad()<<rifile.fail()<<endl;**

   if(!rifile.good()){ cout<<"error reading block "<<blockid<<endl; return -1;}

   rifile.close();
   return 0;
}


回答1:


Quoting the Apache C++ Standard Library User's Guide:

The flag std::ios_base::badbit indicates problems with the underlying stream buffer. These problems could be:
  • Memory shortage. There is no memory available to create the buffer, or the buffer has size 0 for other reasons (such as being provided from outside the stream), or the stream cannot allocate memory for its own internal data, as with std::ios_base::iword() and std::ios_base::pword().
  • The underlying stream buffer throws an exception. The stream buffer might lose its integrity, as in memory shortage, or code conversion failure, or an unrecoverable read error from the external device. The stream buffer can indicate this loss of integrity by throwing an exception, which is caught by the stream and results in setting the badbit in the stream's state.

That doesn't tell you what the problem is, but it might give you a place to start.

Keep in mind the EOF bit is generally not set until a read is attempted and fails. (In other words, checking rifile.good after calling seekg may not accomplish anything.)

As Andrey suggested, checking errno (or using an OS-specific API) might let you get at the underlying problem. This answer has example code for doing that.

Side note: Because rifile is a local object, you don't need to close it once you're finished. Understanding that is important for understanding RAII, a key technique in C++.




回答2:


try old errno. It should show real reason for error. unfortunately there is no C++ish way to do it.



来源:https://stackoverflow.com/questions/2547355/c-file-bad-bit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!