【问题标题】:Is there a way to wait for a file to be written to in pure c++? [duplicate]有没有办法等待用纯 C++ 写入文件? [复制]
【发布时间】:2018-08-15 06:19:32
【问题描述】:

我正在寻找编写一些代码来监控文件。当它被写入时,我想阅读新的行并对其采取行动。

所以我找到了这个帖子:how-to-read-a-growing-text-file-in-c,它向我展示了如何做到这一点。

但是,它有点像“轮询”方法。为方便起见,这里是代码 sn-p。 注意:这不是我的工作(其答案来自链接):

#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)?

我还没有编写任何代码,因为我什至不确定从哪里开始最好。

【问题讨论】:

  • @Marcel,不是“写”而是“写给”:所以每当有人/事物从外部写信给它时。如果开始等待,我想在该文件被修改时醒来。另外 - 这是同一文件系统(无网络)上的本地文件。
  • 未经测试,但我认为您根本不需要睡觉,只需忽略eof()getline() 将阻塞直到出现新数据。默认情况下它会抛出,但显然你可以将流配置为不使用ifs.exceptions(std::ifstream::failbit | std::ifstream::badbit) 这样做,无论如何我会先尝试一下。
  • 也许你可以用inotify知道什么时候有变化......thegeekstuff.com/2010/04/inotify-c-program-example
  • 标准 C++ 库无法做到这一点。骗子确实提供了一个很好的平台特定解决方案列表。在 Linux 上,使用inotify
  • 没有纯 c++ 或 c 方式。您需要使用 OS API,例如用于 Linux 的 Posix 和用于 Windows 的 Windows API。 POSIX:pubs.opengroup.org/onlinepubs/9699919799WINDOWS:docs.microsoft.com/en-us/windows/desktop/api/fileapi/…

标签: c++ file c++11 wait


【解决方案1】:

你只需要添加在Win和Linux上都可以使用的sleep功能,这样你就可以使用它std::this_thread::sleep_for(std::chrono::milliseconds(500)); 在你的代码中。它来自 std 库,因此您可以在 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;
}

【讨论】:

  • 我认为你误读了我的问题......或者我不清楚......但我不是在问如何使用睡眠。我想知道如何等待文件被写入。睡 10 毫秒是完全不同的事情:p
  • 知道了,为此您可以使用QFileSystemWatcher,它具有在文件或文件夹被修改时通知您的功能。由于 Qt 是一个跨平台框架,您的代码将能够在各种操作系统上编译和运行。
  • 这是一个有效的点。我已经使用了很多 Qt,但我真的不想仅仅为此包含 Qt 框架:p
  • 另一种方法是使用 OS API。您可以将它用于 Win 和 Linux,在编译时您可以指定哪个将使用预处理器进行编译。您还需要为它们实现包装器。
猜你喜欢
  • 2019-02-11
  • 2020-05-21
  • 1970-01-01
  • 2021-01-01
  • 2011-10-21
  • 2020-03-23
  • 2019-08-19
  • 1970-01-01
相关资源
最近更新 更多