Кажется, что это должно быть просто, но я не нашел его в сетевом поиске.
У меня есть поток, который равен open()
, а fail()
теперь истинно. Я хотел бы узнать причину отказа открыть, например, с помощью errno
я бы сделал sys_errlist[errno]
.
Кажется, что это должно быть просто, но я не нашел его в сетевом поиске.
У меня есть поток, который равен open()
, а fail()
теперь истинно. Я хотел бы узнать причину отказа открыть, например, с помощью errno
я бы сделал sys_errlist[errno]
.
К сожалению, нет стандартного способа выяснить, почему open() не удалось. Обратите внимание, что sys_errlist не является стандартным С++ (или, как мне кажется, стандартным C).
Функция 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"
}
}
Это переносимо, но, похоже, не дает полезной информации:
#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);
}