2009-06-06 6 views

答えて

5

は残念ながら、()が失敗した理由を正確にオープン見つけ出すの標準的な方法はありません。 sys_errlistは標準のC++ではないことに注意してください。

18

strerrorの機能が<cstring>であると便利です。これは、必ずしも標準またはポータブルではありませんが、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を設定しているわけではないので、絶対に依存することはできません。 –

+0

VS2013アップデート3で動作するように思われる – paulm

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の、我々はブーストを使用する::うまくいくかもしれないの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

これは失敗時に何を表示しますか? – paulm