Обнаружение причины сбоя при открытии ofstream, когда fail () имеет значение - PullRequest
17 голосов
/ 07 июня 2009

Похоже, это должно быть просто, но я не нахожу его в сетевом поиске.

У меня есть ofstream, который равен open(), и fail() теперь верно. Я хотел бы знать причину неудачного открытия, например, с errno Я бы сделал sys_errlist[errno].

Ответы [ 4 ]

19 голосов
/ 07 июня 2009

Может быть полезна функция strerror из <cstring>. Это не обязательно стандартно или переносимо, но для меня это нормально работает с GCC на Ubuntu box:

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

}
5 голосов
/ 07 июня 2009

К сожалению, нет стандартного способа выяснить, почему именно open () не удалось. Обратите внимание, что sys_errlist не является стандартным C ++ (или, как мне кажется, Standard C).

2 голосов
/ 01 декабря 2010

Это портативное устройство, но не дает полезной информации:

#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"
    }
}
0 голосов
/ 10 июля 2013

нам не нужно использовать 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);

}
...