看起来像这样应该很简单,但我在网络搜索中找不到它。检测失败()为true时未能打开ofstream的原因
我有一个ofstream是open()
和fail()
现在是true。我想知道失败的原因,如errno
我会做sys_errlist[errno]
。
看起来像这样应该很简单,但我在网络搜索中找不到它。检测失败()为true时未能打开ofstream的原因
我有一个ofstream是open()
和fail()
现在是true。我想知道失败的原因,如errno
我会做sys_errlist[errno]
。
不幸的是,找出究竟为什么open()的失败的标准方式。请注意,sys_errlist不是标准C++(或标准C,我相信)。
来自<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"
}
}
这是便携式的,但似乎并没有得到有用的信息:
#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);
}
这可能很好地工作,和strerror()是一个标准的C++函数。不幸的是,该标准没有声明open()设置了errno,所以你不能完全依赖它。 – 2009-06-06 22:06:50
似乎在VS2013更新3中工作 – paulm 2015-03-16 16:02:06