gpt4 book ai didi

C++文件坏位

转载 作者:搜寻专家 更新时间:2023-10-31 00:23:04 24 4
gpt4 key购买 nike

当我运行这段代码时,open、seekg 和 tellg 操作全部成功。但是当我读它时,它失败了,eof、bad、fail 位是 0 1 1。

什么会导致文件损坏?谢谢


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;
}

最佳答案

引用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.

这并不能告诉您问题出在哪里,但它可能会给您一个起点。

请记住,EOF 位通常不会设置,直到尝试读取并失败为止。 (换句话说,在调用 seekg 之后检查 rifile.good 可能不会完成任何事情。)

正如 Andrey 所建议的,检查 errno(或使用特定于操作系统的 API)可能会让您找到潜在的问题。 This answer有这样做的示例代码。

旁注:因为 rifile 是本地对象,所以您不需要在完成后关闭它。理解这对理解很重要RAII ,C++ 中的一项关键技术。

关于C++文件坏位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2547355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com