这看起来应该很简单,但我并没有在网上搜索到它。
我有一个ofstream,它是open()
,而fail()
现在是真的。我想知道打开失败的原因,比如使用errno
时,我会使用sys_errlist[errno]
。
发布于 2009-06-06 21:23:17
不幸的是,没有标准的方法来找出open()失败的确切原因。请注意,sys_errlist不是标准的C++ (我相信也不是标准的C )。
发布于 2009-06-06 21:18:14
<cstring>
中的strerror函数可能很有用。这不一定是标准的或可移植的,但对于我在Ubuntu机器上使用GCC来说,它工作得很好:
#include <iostream>
using std::cout;
#include <fstream>
using std::ofstream;
#include <cstring>
using std::strerror;
#include <cerrno>
int main() {
ofstream fout("read-only.txt"); // file exists and is read-only
if( !fout ) {
cout << strerror(errno) << '\n'; // displays "Permission denied"
}
}
发布于 2010-12-01 05:48:03
这是可移植的,但似乎没有提供有用的信息:
#include <iostream>
using std::cout;
using std::endl;
#include <fstream>
using std::ofstream;
int main(int, char**)
{
ofstream fout;
try
{
fout.exceptions(ofstream::failbit | ofstream::badbit);
fout.open("read-only.txt");
fout.exceptions(std::ofstream::goodbit);
// successful open
}
catch(ofstream::failure const &ex)
{
// failed open
cout << ex.what() << endl; // displays "basic_ios::clear"
}
}
https://stackoverflow.com/questions/960541
复制相似问题