看起来这应该很简单,但我在网络搜索中找不到它。
我有一个 ofstream 是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"
}
}
我们不需要使用 std::fstream,我们使用 boost::iostream
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
void main()
{
namespace io = boost::iostreams;
//step1. open a file, and check error.
int handle = fileno(stdin); //I'm lazy,so...
//step2. create stardard conformance streem
io::stream<io::file_descriptor_source> s( io::file_descriptor_source(handle) );
//step3. use good facilities as you will
char buff[32];
s.getline( buff, 32);
int i=0;
s >> i;
s.read(buff,32);
}