2013-04-03 76 views
2

我一直有奇怪的问题写有ofstreams到文件,现在有C++调试ofstream失败()状态?

ofstream.fail() 

是我ofstream.open()调用后返回true权。

是否有一些获取附加信息的方法,例如关于为什么设置失败状态的更多细节?

编辑,附加信息:is_open()返回false。

+0

是什么'IS_OPEN()'说什么? – jrok

+0

is_open()返回false。 – user788171

+0

据此.. http://www.cplusplus.com/reference/ios/ios/fail/我猜这个函数不会帮你挖掘失败的真正原因... –

回答

0
io_state word=ofstream.rdstate(); 
if(word & ios::failbit){ 
    cout<<"Failbit flag is set"; 
} 
//etc 
1

确保ofstream没有与它已经相关的文件(打开与流的文件的话)。根据http://www.cplusplus.com/reference/fstream/ofstream/open/

如果对象已经有一个文件关联(打开),则该函数将失败。 失败时,将设置失败位标志(可以使用成员失败进行检查),并根据异常设置的值来抛出异常。

如果您打开了一个文件,请在打开之前将其关闭。

编辑:如上图所示,你可以检查哪些'failbit flag通过使用stream.rdstate()

1

刚刚设定发现了同样的情况,我决定,读过

如果(outfile.is_open一个错字()! );

{

}

的,如果statment后没有注意到分号...

0

报价this

std::string DescribeIosFailure(const std::ios& stream) 
{ 
    std::string result; 

    if (stream.eof()) { 
    result = "Unexpected end of file."; 
    } 

#ifdef WIN32 
    // GetLastError() gives more details than errno. 
    else if (GetLastError() != 0) { 
    result = FormatSystemMessage(GetLastError()); 
    } 
#endif 

    else if (errno) { 
#if defined(__unix__) 
    // We use strerror_r because it's threadsafe. 
    // GNU's strerror_r returns a string and may ignore buffer completely. 
    char buffer[255]; 
    result = std::string(strerror_r(errno, buffer, sizeof(buffer))); 
#else 
    result = std::string(strerror(errno)); 
#endif 
    } 

    else { 
    result = "Unknown file error."; 
    } 

    boost::trim_right(result); // from Boost String Algorithms library 
    return result; 
}