首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在ifstream打开失败时获取错误信息

如何在ifstream打开失败时获取错误信息
EN

Stack Overflow用户
提问于 2013-06-27 15:51:38
回答 3查看 130.8K关注 0票数 117
代码语言:javascript
复制
ifstream f;
f.open(fileName);

if ( f.fail() )
{
    // I need error message here, like "File not found" etc. -
    // the reason of the failure
}

如何以字符串的形式获取错误信息?

EN

回答 3

Stack Overflow用户

发布于 2016-04-14 12:35:51

根据@Arne Mertz的回答,从C++11开始,std::ios_base::failure继承自system_error (请参阅http://www.cplusplus.com/reference/ios/ios_base/failure/),其中包含strerror(errno)将返回的错误代码和消息。

代码语言:javascript
复制
std::ifstream f;

// Set exceptions to be thrown on failure
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);

try {
    f.open(fileName);
} catch (std::system_error& e) {
    std::cerr << e.code().message() << std::endl;
}

如果fileName不存在,则输出No such file or directory.

票数 26
EN

Stack Overflow用户

发布于 2018-07-01 06:27:07

您还可以抛出一个std::system_error,如下面的测试代码所示。这种方法产生的输出似乎比f.exception(...)更具可读性。

代码语言:javascript
复制
#include <exception> // <-- requires this
#include <fstream>
#include <iostream>

void process(const std::string& fileName) {
    std::ifstream f;
    f.open(fileName);

    // after open, check f and throw std::system_error with the errno
    if (!f)
        throw std::system_error(errno, std::system_category(), "failed to open "+fileName);

    std::clog << "opened " << fileName << std::endl;
}

int main(int argc, char* argv[]) {
    try {
        process(argv[1]);
    } catch (const std::system_error& e) {
        std::clog << e.what() << " (" << e.code() << ")" << std::endl;
    }
    return 0;
}

输出示例(Ubuntu w/clang):

代码语言:javascript
复制
$ ./test /root/.profile
failed to open /root/.profile: Permission denied (system:13)
$ ./test missing.txt
failed to open missing.txt: No such file or directory (system:2)
$ ./test ./test
opened ./test
$ ./test $(printf '%0999x')
failed to open 000...000: File name too long (system:36)
票数 10
EN

Stack Overflow用户

发布于 2021-02-17 01:54:52

上面的std::system_error示例稍有不正确。std::system_category()将从系统的本地错误代码工具映射错误代码。对于*nix,这是errno。对于Win32,它是GetLastError()。即,在Windows上,上面的示例将打印出来

代码语言:javascript
复制
failed to open C:\path\to\forbidden: The data is invalid

因为EACCES是13,这是Win32错误代码ERROR_INVALID_DATA

要修复它,可以使用系统的本地错误代码工具,例如在Win32上

代码语言:javascript
复制
throw new std::system_error(GetLastError(), std::system_category(), "failed to open"+ filename);

或者使用errno和std::generic_category(),例如

代码语言:javascript
复制
throw new std::system_error(errno, std::generic_category(), "failed to open"+ filename);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17337602

复制
相关文章

相似问题

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