Rilevamento motivo per la mancata apertura di un ofstream quando fail () è vera
Domanda
Sembra che questo deve essere semplice, ma io non lo trovo in una ricerca in rete.
Ho un ofstream che è open()
, e fail()
ora è vero. Mi piacerebbe sapere il motivo della mancata apertura, come con errno
lo farei sys_errlist[errno]
.
Soluzione
Purtroppo, non v'è alcun modo standard di scoprire esattamente il motivo per open () non è riuscita. Si noti che sys_errlist non è standard C ++ (o Standard C, credo).
Altri suggerimenti
Il strerror funzione dal <cstring>
potrebbe essere utile. Questo non è necessariamente standard o portatile, ma funziona bene per me utilizzando GCC su una casella di 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"
}
}
Questa è portatile, ma non sembra dare informazioni utili:
#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"
}
}
non abbiamo bisogno di usare std :: fstream, usiamo 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);
}