我有一些将系统时间写入文件的代码:
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/