c++ - 使用 Sleep() 阻止我写入文件

标签 c++ sleep

我有一些将系统时间写入文件的代码:

std::ofstream file("time.txt");

    char *date;
    time_t timer;
    timer=time(NULL);
    date = asctime(localtime(&timer));

while ( true ) {
      std::cout << date << ", " << randomNumber  << std::endl;

      if (file.is_open())
      {
        file << date;
        file << ", ";
        file << randomNumber;
        file << "\n";
      }
}

file.close()

当我让我的程序运行并在其间停止时(它是一个无限循环),我能够将数据写入我的文件。

但是,如果我只是更改代码以添加一个 Sleep() 计时器。没有数据写入我的文件。但我确实在屏幕上看到了输出。这是预期的行为吗?如何确保即使我中途结束程序执行,值也会写入文件?

    std::ofstream file("time.txt");

        char *date;
        time_t timer;
        timer=time(NULL);
        date = asctime(localtime(&timer));

    while ( true ) {

        **Sleep(100); // wait for 100 milli-seconds**
          std::cout << date << ", " << randomNumber  << std::endl;

          if (file.is_open())
          {
            file << date;
            file << ", ";
            file << randomNumber;
            file << "\n";
          }
    }

    file.close()

如果我在 sleep 计时器结束后立即关闭我的文件,它会写出数据。但我添加计时器的主要原因是我想减慢我的文件写入的频率......

最佳答案

您需要刷新缓冲区,以便将内容写入文件。调用std::flush或更改 file << "\n";file << std::endl;冲洗流。当你不打电话时 Sleep在你的程序中,一旦缓冲区变满,缓冲区的内容就会被写入,但是,Sleep由于存在延迟,缓冲区不会立即变满,因此您看不到写入文件的内容。

关于c++ - 使用 Sleep() 阻止我写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14371520/

相关文章:

linux - 在超过十亿个文件的目录执行 "tar"时,进程停留在D状态

python - time.sleep() 和 BackGround Windows PyQt5

c - 我的函数 'sleep' 阻止其他进程

javascript - sleep() 的 JavaScript 版本是什么?

python - 如何从 cv::Mat(在 C++ 中)转换为 tf.placeholder(在 C++ Boost.Python 中)?

c++ - NtDeviceIoControlFile(查询 IP 地址条目)- STATUS_INVALID_DEVICE_REQUEST

c++ - 与二维数组有关的循环崩溃程序

c++ - Operator new 返回比请求更多的内存

c++ - mingw下Qt 5静态编译失败引用off64_t

c++ - 睡了很多天,分辨率为微秒