Подтвердить что ты не робот

Обнаружение причины сбоя открытия потока, когда fail() истинно

Кажется, что это должно быть просто, но я не нашел его в сетевом поиске.

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

4b9b3361

Ответ 1

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

Ответ 2

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

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

}

Ответ 3

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

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

Ответ 4

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

}