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

时间:2016-03-09 19:10:36

标签: c++ exception try-catch throw

我尝试使用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;
}

任何想法为什么?我已经查看了read函数的返回值,但无法找到这种行为的答案。

2 个答案:

答案 0 :(得分:2)

我认为ifstream::read未设置errno值。如果读取的字节数超过可用字节,则只读设置failbiteofbit。您应该使用rdstate来获取这两位的值而不是errno

<强>更新

要检查是否设置了failbiteofbit,请将它们与rdstate()返回值进行比较

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

答案 1 :(得分:2)

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

当ifstream :: read尝试在72字节缓冲区中读取1000个字节时,会触发异常而不是ifstream :: read的句柄,它只会返回“success”(内部ifstream :: read必须在返回的变量中返回代码) begining)

我建议你采用这种方法:

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));
...