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

时间:2009-06-06 21:07:58

标签: c++ iostream

似乎这应该很简单,但我没有在网络搜索中找到它。

我有一个open()的ofstream,而fail()现在是真的。我想知道未能打开的原因,例如errno我会做sys_errlist[errno]

4 个答案:

答案 0 :(得分:19)

来自<cstring>的{​​{3}}功能可能很有用。这不一定是标准的或可移植的,但它对我在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"
  }

}

答案 1 :(得分:5)

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

答案 2 :(得分:2)

这是便携式的,但似乎没有提供有用的信息:

#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"
    }
}

答案 3 :(得分:-3)

我们不需要使用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);

}