0

The essence of my problem is that I can't write to a file in a loop with sleep(). If I have the following code:

ofstream file
file.open("file.name");

for(;;) {
    file << "HELLO\n";
}

This code works perfectly and prints HELLO repeatedly into "file.name". However, I want to do something like this (I'm recording data from a real-time application):

for(;;) {
    file << "HELLO\n";
    sleep(1);
}

This doesn't seem to print anything into my file. Any ideas?

Roddy
  • 66,617
  • 42
  • 165
  • 277
vette982
  • 4,782
  • 8
  • 34
  • 41

3 Answers3

6

You need to flush the output. The output stream is buffering your data into memory but not writing it out to disk. You should either use std::endl (which prints a newline and flushes) instead of the string literal '\n', or explicitly flush the stream with std::flush:

for(;;) {
    file << "HELLO" << endl;
}
// or
for(;;) {
    file << "HELLO\n" << flush;
}
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • Excellent, thank you! In the mean time I made a quick fix by repeatedly opening and closing the file handle in each iteration of the loop, which must have accomplished the flush. – vette982 Jul 13 '11 at 00:13
3

The magic word you are looking for is "flush".

c++ std::ofstream flush() but not close()

before the sleep, flush the file so that it isn't pending in a buffer waiting for there to be enough of a change to bother writing out.

Community
  • 1
  • 1
Mark
  • 1,058
  • 6
  • 13
2

It's probably just a buffering issue. Because you are now writing much slower, the output buffer wont fill up so fast so you may not 'see' the written data. Try adding a flush() before the sleep.

file.flush()
Roddy
  • 66,617
  • 42
  • 165
  • 277