Reputation: 679
I have some code that writes the system time to a file:
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()
When I let my program run and stop it in-between (its an infinite while loop), I am able to get data written to my file.
However, if I merely change the code to add a Sleep() timer. No data is written to my file. But I do see an output on the screen. Is this expected behavior? How do I ensure that even if I end my program execution mid-way, values are written to the file?
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()
If I close my file right after the sleep timer, it writes the data out. But the main reason I'm adding the timer, is that I want to slow-down how often my file is being written to ...
Upvotes: 1
Views: 462
Reputation: 52365
You need to flush the buffer so the contents are written to the file. Call std::flush
or change file << "\n";
to file << std::endl;
to flush the stream. When you don't call Sleep
in your program, the contents of the buffer are written as soon as the buffer becomes full, however, with Sleep
the buffer doesn't become full right away because there is a delay, so you don't see the contents written to the file.
Upvotes: 3