当fail()为真时,检测无法打开ofstream的原因

Wil*_*mKF 17 c++ iostream

看起来这应该很简单,但我没有在网络搜索中找到它.

我有一个ofstream的是open(),而且fail()现在是真实的.我想知道失败的原因,就像errno我会这样做sys_errlist[errno].

Nat*_*ohl 19

字符串错误的功能<cstring>可能是有用的.这不一定是标准的或可移植的,但它对我在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"
  }

}
Run Code Online (Sandbox Code Playgroud)

  • 这可能很有用,而strerror()是标准的C++函数.不幸的是,标准没有说open()设置errno,所以你不能完全依赖它. (6认同)

小智 5

不幸的是,没有标准的方法可以找出open()失败的确切原因.请注意,sys_errlist不是标准C++(或标准C,我相信).