2009-06-06 25 views

Trả lời

5

Thật không may, không có cách nào tiêu chuẩn của việc tìm hiểu chính xác lý do tại sao open() thất bại. Lưu ý rằng sys_errlist không phải là tiêu chuẩn C++ (hoặc Standard C, tôi tin).

18

Chức năng strerror từ <cstring> có thể hữu ích. Đây không phải là nhất thiết phải chuẩn hoặc di động, nhưng nó hoạt động ổn cho tôi sử dụng GCC trên một hộp 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

Đó cũng có thể làm việc, và strerror() là hàm C++ chuẩn. Thật không may, tiêu chuẩn không nói rằng các tập mở() đặt sai, vì vậy bạn không thể hoàn toàn phụ thuộc vào nó. –

+0

Dường như hoạt động trong Bản cập nhật VS2013 3 – paulm

2

Đây là di động nhưng không xuất hiện để cung cấp cho thông tin hữu ích:

#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

chúng tôi không cần phải sử dụng std :: fstream, chúng tôi sử dụng tăng :: 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

Vì vậy, điều này sẽ hiển thị gì đối với lỗi? – paulm

Các vấn đề liên quan