我的fstream总是返回true,即使文件名错误?

时间:2012-02-17 04:10:59

标签: c++

这是我的第一个问题,我真的无法弄清楚这一点。在调试之后,我意识到无论什么内容被放入outFileName,反过来outFile,它总是返回true并且不会显示错误消息。很抱歉,如果我遗漏了任何内容,这就是c ++我正在使用visual studio 2010让我知道是否需要添加任何问题。

        inFile.open(fileName.c_str(), ios::in);
        outFile.open(outFileName.c_str(), ios::out);
        if (inFile.good() == false && outFile.good() == false)
        {
            cerr << strerror(errno) << endl;
            cerr << "Problem with the input and output file" << endl;
            continue;
        }

        else if (inFile.good() == true &&
                 outFile.good() == false)
        {
            cerr << strerror(errno) << endl;
            cerr << "Problem with the output file";
            continue;
        }
        else if (outFile.good() == true &&
                inFile.good() == false)
        {
            cerr << strerror(errno) << endl;
            cerr << "Problem with the input file" << endl;
        }

2 个答案:

答案 0 :(得分:2)

如果要写入现有文件,可能要删除现有内容(覆盖它),否则添加到最后。所以合理的标志是:

outFile.open(outFileName.c_str(), ios::in | ios::out | ios::trunc);

outFile.open(outFileName.c_str(), ios::in | ios::out | ios::app | ios::ate);

这些将要求文件已存在。

之后,outFile.good()返回一个可以直接测试的布尔值。不要将它与true进行比较。毕竟,如果outFile.good() == true为真,则outFile.good()必须为真。实际上,流有一个显式的转换为boolean,以及用户定义的operator!()。因此,您的错误检查可能如下所示:

if (!inFile) {
    if (!outFile) {
        cerr << strerror(errno) << endl
             << "Problem with the input and output file" << endl;
    }
    else {
        cerr << strerror(errno) << endl
             << "Problem with the input file";
    }
}
else if (!outFile) {
    cerr << strerror(errno) << endl
         << "Problem with the output file" << endl;
}

答案 1 :(得分:0)

如果您有权打开文件进行书写,那么它永远不会失败。

尝试在不允许打开的位置打开文件。

相关问题