简体   繁体   English

执行文件I / O时出现意外的异常结果

[英]Unexpected results on exception while doing file I/O

I have a small code with some file I/O 我有一些文件I / O的小代码

bool loadConfigFile(std::string configFileName)
{
    std::ifstream configFile;
    try
    {
        configFile.open(configFileName, std::ifstream::in);
        if(true != configFile.good())
        {
            throw std::exception("Problem with config file");
        }
    } catch (std::exception &e)
    {
        fprintf(stderr, "There was an error while opening the file: %s\n %s\n" , configFileName, e.what());
        configFile.close();
    }

    configFile.close();
    return true;
}

And everytime I launch the program without the file provided as a parameter I get some rubbish on output (random characters) or an unexpected error in runtime. 每次我启动程序时都没有提供作为参数的文件时,都会在输出(随机字符)或运行时出现意外错误时产生一些垃圾。 What am I doing wrong here ? 我在这里做错了什么?

"%s" expects an null terminated char array as its input but the code is passing configFileName , which is a std::string . "%s"期望以null终止的char数组作为其输入,但是代码正在传递configFileName ,它是std::string Either use std::string::.c_str() or use std::cerr instead: 使用std::string::.c_str()或使用std::cerr代替:

std::cerr << "There was an error while opening the file: "
          << configFileName << '\n'
          << e.what()       << '\n';

Note that the ifstream constructor has a variant that accepts the filename to open and the destructor will close the stream if it is open so the explicit calls to open() and close() can be omitted: 请注意, ifstream构造函数具有一个接受打开文件名的变体,并且析构函数将在打开流时关闭该流,因此可以省略对open()close()的显式调用:

try
{
    std::ifstream configFile(configFileName);
    if (!configFile.is_open())
    {
        throw std::exception("Failed to open '" + configFileName + "'");
    }
}
catch (const std::exception& e)
{
    // Handle exception.
    std::cerr << e.what() << '\n';
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM