gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:40:46 24 4
gpt4 key购买 nike

这是我的第一个问题,我真的想不通。调试后我意识到无论将什么放入 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;
}

最佳答案

如果您想写入现有文件,您可能想要删除现有内容(覆盖它),或者添加到末尾。所以合理的标志是:

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() 返回一个 bool 值,您可以直接对其进行测试。不要将它与 true 进行比较。毕竟,如果 outFile.good() == true 为真,则 outFile.good() 一定为真。事实上,对于流,以及用户定义的 operator!() 都有一个到 boolean 的显式转换。因此,您的错误检查可能如下所示:

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;
}

关于c++ - 我的 fstream 总是返回 true,即使文件名错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9322776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com