有没有办法等待文件在纯 c++ 中写入?

Is there a way to wait for a file to be written to in pure c++?

本文关键字:c++ 等待 文件 有没有      更新时间:2023-10-16

我想写一些代码来监视文件。当它被写到时,我想阅读新行并采取行动。

所以我找到了这个线程:如何阅读增长文本文件,它向我展示了如何做到这一点。

但是,这是一种"轮询"方法。为方便起见,以下是代码片段。注意:这不是我的工作(这是链接中的答案(:

#include <iostream>
#include <string>
#include <fstream>
int main()
{
std::ifstream ifs("test.log");
if (ifs.is_open())
{
std::string line;
while (true)
{
while (std::getline(ifs, line)) std::cout << line << "n";
if (!ifs.eof()) break; // Ensure end of read was EOF.
ifs.clear();
// You may want a sleep in here to avoid
// being a CPU hog.
}
}
return 0;
}

你可以看到有评论:You may want a sleep in here to avoid being a CPU hog.

有没有办法(可能没有(等待文件被写入,以便某些事件/条件触发我们的线程唤醒?我正在沿着类似select()功能的方式思考......但我真的希望它是纯粹的 c++。

失败了 - 是否有一种非纯 c++ 方式(对我来说,我需要它适用于 Linux 操作系统,也可能适用于 Windows(?

我还没有编写任何代码,因为我甚至不确定最好的起点在哪里。

你只需要添加同时适用于Win和Linux的睡眠函数,因此你可以使用它std::this_thread::sleep_for(std::chrono::milliseconds(500));在您的代码中。它来自标准库,因此您可以在Linux或Windows上使用它。

#include <chrono>
#include <thread>
#include <iostream>
#include <string>
#include <fstream>
int main()
{
std::ifstream ifs("test.log");
if (ifs.is_open())
{
std::string line;
while (true)
{
while (std::getline(ifs, line)) std::cout << line << "n";
if (!ifs.eof()) break; // Ensure end of read was EOF.
ifs.clear();
// You may want a sleep in here to avoid
// being a CPU hog.
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
return 0;
}