このように単純なはずですが、ネット検索では見つかりません。
私は、現在は真実であるオフストリームを持っていopen()
ますfail()
。私と同じように、開かない理由を知りerrno
たいのですがsys_errlist[errno]
。
のstrerror関数<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"
}
}
残念ながら、open() が失敗した理由を正確に突き止める標準的な方法はありません。sys_errlist は標準 C++ (または標準 C だと思います) ではないことに注意してください。
これは移植可能ですが、有用な情報を提供していないようです。
#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"
}
}