首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >当fail()为true时检测打开ofstream失败的原因

当fail()为true时检测打开ofstream失败的原因
EN

Stack Overflow用户
提问于 2009-06-06 21:07:58
回答 4查看 16.6K关注 0票数 17

这看起来应该很简单,但我并没有在网上搜索到它。

我有一个ofstream,它是open(),而fail()现在是真的。我想知道打开失败的原因,比如使用errno时,我会使用sys_errlist[errno]

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-06-06 21:23:17

不幸的是,没有标准的方法来找出open()失败的确切原因。请注意,sys_errlist不是标准的C++ (我相信也不是标准的C )。

票数 5
EN

Stack Overflow用户

发布于 2009-06-06 21:18:14

<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"
  }

}
票数 19
EN

Stack Overflow用户

发布于 2010-12-01 05:48:03

这是可移植的,但似乎没有提供有用的信息:

#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"
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/960541

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档