2009-06-06 112 views

回答

5

不幸的是,找出究竟为什么open()的失败的标准方式。请注意,sys_errlist不是标准C++(或标准C,我相信)。

18

来自<cstring>strerror函数可能会有用。这不一定是标准的或便携式的,但它使用的Ubuntu箱GCC工作好对我来说:

#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

这可能很好地工作,和strerror()是一个标准的C++函数。不幸的是,该标准没有声明open()设置了errno,所以你不能完全依赖它。 – 2009-06-06 22:06:50

+0

似乎在VS2013更新3中工作 – paulm 2015-03-16 16:02:06

2

这是便携式的,但似乎并没有得到有用的信息:

#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

我们不必使用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); 

}