c++ - 检查ifstream,出错后不起作用?

标签 c++ ifstream

我在下面附上了我的代码。如果我删除 if 语句以检查文件是否已打开,此序列将起作用。为什么它不能与 if 语句一起使用?此外,如果我第一次提供正确的文件名,它的工作方式如下所示。只有当我先输入错误的文件名时它才会挂断。

感谢您的帮助!

ifstream inputFile(fileName.c_str());

if(!inputFile)
{
    cout << "Unable to locate input file, please ensure it is in the working directory"
         << endl;
    cout << "Enter the name of your input file (ex. input.txt):  ";
    cin >> fileName;
    cout << endl;

    ifstream inputFile(fileName.c_str());
}
else
{
    cout << "Input file opened successfully!" << endl;
}

最佳答案

你显示的代码是完全合法的,所以我想你在这个“错误的文件名”逻辑之后使用 inputFile:

ifstream inputFile(fileName.c_str());

if(!inputFile)
{
    cout << "Unable to locate input file, please ensure it is in the working directory"
         << endl;
    cout << "Enter the name of your input file (ex. input.txt):  ";
    cin >> fileName;
    cout << endl;

    ifstream inputFile(fileName.c_str());
}
else
{
    cout << "Input file opened successfully!" << endl;
}
// USING inputFile here

问题在于,您在这里仍然拥有原始的 inputFileif 语句中的 inputFile 是一个new std::ifstream。如果您使用不同的名称,可能会更容易看出:

ifstream inputFile(fileName.c_str());

if(!inputFile)
{
    cout << "Unable to locate input file, please ensure it is in the working directory"
         << endl;
    cout << "Enter the name of your input file (ex. input.txt):  ";
    cin >> fileName;
    cout << endl;

    ifstream differentInputFile(fileName.c_str()); //HERE
}
else
{
    cout << "Input file opened successfully!" << endl;
}

关闭坏文件并用正确的文件名重新打开的正确方法是:

inputFile.close();
inputFile.open(fileName.c_str());

那么完整的代码就变成了

ifstream inputFile(fileName.c_str());

if(!inputFile)
{
    cout << "Unable to locate input file, please ensure it is in the working directory"
         << endl;
    cout << "Enter the name of your input file (ex. input.txt):  ";
    cin >> fileName;
    cout << endl;

    inputFile.close();
    inputFile.open(fileName.c_str());
}
else
{
    cout << "Input file opened successfully!" << endl;
}

还建议启用警告。我的建议是使用 -Wall -Wextra -Wshadow -pedantic -Wfatal-errors(适用于 gcc 和 clang)。

关于c++ - 检查ifstream,出错后不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29242952/

相关文章:

C++ ifstream 跳过第一行

c++ - 序列化 : CArchive a CImage

c++ - 关于将 const 引用绑定(bind)到临时对象的子对象

c++ - 写入二进制文件时数据丢失-C++

c++ - 从文件中读取浮点值会删除全部或部分小数部分

c++ - 如何读入文件的末尾(或刚好在末尾之前)的字符?

c++ - 还有几个 SWIG 警告

c++ - 将boost库链接到C++项目

c++ - 复制构造函数类

c++ - 从同一个文件读取和写入?