2009-06-06 22 views

Odpowiedz

5

Niestety, nie ma standardowy sposób dowiedzieć się dokładnie, dlaczego open() nie powiodło się. Zauważ, że sys_errlist nie jest standardowym C++ (lub, jak sądzę, standardowym C).

18

Funkcja strerror z <cstring> może być przydatna. Niekoniecznie jest to standardowy lub przenośny, ale działa dobrze dla mnie za pomocą GCC na polu 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" 
    } 

} 
+5

To może dobrze pracować, a strerror() jest standardową funkcją C++. Niestety, standard nie stwierdza, że ​​open() ustawia errno, więc nie można na nim całkowicie polegać. –

+0

Wydaje się działać w aktualizacji VS2013 3 – paulm

2

To jest przenośny, ale nie wydaje się, aby dać użyteczną informację:

#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

nie musimy używać std :: fstream, używamy 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); 

} 
+1

Co to będzie wyświetlać po awarii? – paulm

Powiązane problemy