读取功能失败时的成功消息

Success message when read function fails

我正在尝试使用 ifstream 和所有 try and catch 方法打开文件。我想测试读取功能。当我尝试阅读更多文件长度时,我遇到了异常。但是报错信息:

Error:basic_ios::clear: Success

我的代码:

    void OpenFile(char* raw_slice) throw(std::ios_base::failure, std::string) {

        ifstream init;
        init.exceptions(ifstream::failbit | ifstream::badbit | ifstream::eofbit);
        try {
             init.open("/home/path/file", ios_base::in | ios_base::binary );
       }catch(const ifstream::failure &e) {
             cerr << "Error:" << e.what() << ": " << strerror(errno) << endl;
             throw;
       }
       try {
             init.read((char*)raw_slice, 1000); //out of bound of source file
       }catch (const ifstream::failure &e){
             cerr << "Error:" << e.what() << ": " <<  strerror(errno) << endl;
       throw;
       }
       try{
            init.close();
       }catch(const ifstream::failure &e){
            cerr << "Error:"<< e.what() << ": " << strerror(errno) << endl;
           throw;
       }
    }

int main()
{
    char* buf = new char[72];
    try{
        OpenFile(buf);
    }catch (const ifstream::failure &e){
        cerr << "Error in main:" << e.what() << ": " << strerror(errno) << endl;
        delete[] buf;
        return 0;
    }catch (const string &e) {
        cerr << "Error in main:: " << e << endl;
        delete[] buf;
        return 0;
    ``}
    delete[] buf;
    return 1;
}

知道为什么吗?我查看了读取函数的 return 值,但找不到此行为的答案。

我认为 ifstream::read 没有设置 errno 值。在读取超过可用字节的情况下,只读设置 failbiteofbit。您应该使用 rdstate 而不是 errno 来获取这两位的值。


更新

检查是否设置了 failbiteofbit 将它们与 rdstate() return 值

进行比较
if ( (init.rdstate() & std::ifstream::failbit ) != 0 && (init.rdstate() & std::ifstream::eofbit ) != 0 )
    cerr << "Error: reached end of file before reading all required bytes\n";

您的代码有一个错误:init.read((char*)raw_slice, 1000); 需要一个 1000 字节的缓冲区,但您正在传递使用 char* buf = new char[72];

创建的 72 字节缓冲区

当 ifstream::read 尝试读取 72 字节缓冲区中的 1000 字节时引发异常,无法为 ifstream::read 处理,它只是 return 使您 "success"(内部 ifstream::read 必须在变量中初始化 return 代码)

我建议你这个方法:

void OpenFile(char* raw_slice, int buffer_size) throw(std::ios_base::failure, std::string) {

    ifstream init;
    init.exceptions(ifstream::failbit | ifstream::badbit | ifstream::eofbit);
    try {
         init.open("/home/path/file", ios_base::in | ios_base::binary );
   }catch(const ifstream::failure &e) {
         cerr << "Error:" << e.what() << ": " << strerror(errno) << endl;
         throw;
   }
   try {
         init.read((char*)raw_slice, buffer_size); //out of bound of source file
   }catch (const ifstream::failure &e){
         cerr << "Error:" << e.what() << ": " <<  strerror(errno) << endl;
   throw;
   }
   try{
        init.close();
   }catch(const ifstream::failure &e){
        cerr << "Error:"<< e.what() << ": " << strerror(errno) << endl;
       throw;
   }
}

int main()
{
   char* buf = new char[72];
   try{
       OpenFile(buf, sizeof(buf));
...