我正在使用一会儿true来查找Pass.txt文件。
一旦找到它,while循环就会中断并打印
"Pass.txt file FOUND"
这很好像这样的
ifstream ifile("Pass.txt || Fail.txt");
这不起作用: cout << " ------------------------------------------\n";
cout << " Searching for Pass or Fail file \n";
cout << " ------------------------------------------\n";
cout << "\n\n";
while (true)
{
ifstream ifile("Pass.txt");
//ifstream ifile("Pass.txt ||Fail.txt");
if (ifile)
{
// The file exists, and is open for input
break;
}
}
cout << "\n\n";
cout << " ------------------------------------------\n";
cout << " Pass.txt FOUND \n";
cout << " ------------------------------------------\n";
cout << " ------------------------------------------\n";
最佳答案
您的代码失败,因为您没有测试是否存在两个文件。您正在测试是否存在一个名称奇怪的文件Pass.txt || Fail.txt
的文件。您需要进行两次单独的存在性检查,每个单独的文件一项。
为此,请不要打开文件-使用 std::filesystem::exists
:
#include <filesystem>
#include <thread>
// …
int main() {
using namespace std::chrono_literals;
namespace fs = std::filesystem;
while (not fs::exists("Pass.txt")) {
std::this_thread::sleep_for(500ms); // Be gentle to the system.
}
while (not (fs::exists("Pass.txt") or fs::exists("Fail.txt"))) {
std::this_thread::sleep_for(500ms); // Be gentle to the system.
}
}
(您也可以写!
代替not
,用||
代替or
;但是我更喜欢在自己的代码中使用这些描述性术语。)我们使用
std::this_thread::sleep
来避免使用busy loop破坏系统,即使您的代码没有做任何实际工作,这也会使CPU疯狂运转。但是请注意,仅测试文件的存在不是很有用。您的第二个循环将立即终止,因为
"Pass.txt"
在第一个循环之后存在(除非是偶然的巧合,它在两个循环之间的纳秒内被删除了)。