检查ifstream,错误后无效?

时间:2015-03-24 21:10:44

标签: 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;
}

1 个答案:

答案 0 :(得分:1)

您展示的代码完全合法,因此我认为您在此之后使用inputFile&#34;错误的文件名&#34;逻辑:

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

问题在于,您仍然拥有原始inputFileinputFile语句中的if 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来说)。