0

I have a program that looks like this. I need to consistently write something into a text file but I cannot predetermine when the program is going to end. So I force quit the program.

FILE *f = fopen("text.txt", "w");
while (1) {
    fprintf(f, "something");
    sleep(1000);
}

The problem is that the text file would be empty. Can anyone give me some suggestions? I am using XCode to do the job.

Ruofeng
  • 2,180
  • 3
  • 14
  • 15
  • you may have a look at this question http://stackoverflow.com/questions/914613/what-exactly-is-the-effect-of-ctrl-c-on-c-win32-console-applications it is windows specific but the second answer may give you an idea – Alessandro Teruzzi Apr 03 '12 at 15:49

2 Answers2

3

Use fflush(f) after fprintf(f) otherwise the data you printed is still in the stream buffers in stdio and hasn't yet reached the filesystem.

Note that doing this very often may dramatically reduce your performance.

Eddie Edwards
  • 428
  • 2
  • 5
0

Another way to write in files would be to use the append mode and close the file when you don't need it.

while (1) {
  FILE *f = fopen("text.txt", "a");
  if (f != NULL) {
    fprintf(f, "something");
    fclose(f);
  }
  sleep(1000);
}

In your case, if you 'force-quit' during a sleep phase, the file will not be opened at this time.

SirDarius
  • 41,440
  • 8
  • 86
  • 100