有没有办法等待文件在纯 c++ 中写入?
Is there a way to wait for a file to be written to in pure c++?
我想写一些代码来监视文件。当它被写到时,我想阅读新行并采取行动。
所以我找到了这个线程:如何阅读增长文本文件,它向我展示了如何做到这一点。
但是,这是一种"轮询"方法。为方便起见,以下是代码片段。注意:这不是我的工作(这是链接中的答案(:
#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;
}
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 如何让LLDB在成功时退出,在失败时等待
- 等待整个 omp 块完成,然后再调用第二个函数
- 提升 ASIO - io_service 不要等待连接到线程
- 如何在C++中实现带有packaged_task的异步等待循环?
- 虚假唤醒是否会解锁所有等待线程,甚至是不相关的线程?
- 如何等待窗口隐藏在Qt中?
- 如何在不等待检索的情况下获取C++中的内存位置?
- 等待被迷住了,没有回来
- 等待 WaitForMultipleObjects 窗口中的事件数量可变
- 一个线程等待多个线程事件
- 等待 qthread 终止的正确方法是什么?
- 不可预测的C++睡眠/等待行为
- Bison/flex 在识别规则后等待输入
- 使用记事本C++打开 txt 文件时无需等待
- 接受函数在发送数据包时等待
- 在Visual Studio中运行/调试C ++时,如何在结束时等待输入
- 对于等待以 std::future wait() 返回的函数的 CPU 使用率或检查标志在循环中休眠一段时间哪个更好?
- 在等待时破坏condition_variable
- 如何处理 RAII 中的资源等待