0

I'm currently redirecting NSLog() output to a file using a call to freopen() from the App Delegate. I would like to restrict the log file size, but doing this-

  unsigned long long fs = 3000;
  while ([fileAttributes fileSize] < fs) {

    freopen([FILEPATH cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);

  }

causes the app to be stuck with a black screen in an infinite loop. Is there any way I can set a buffer size for stderr, and then have a loop wherein I only continue to write to the file if the filesize + buffer size does not exceed the file size?

Apophenia Overload
  • 2,485
  • 3
  • 28
  • 46

2 Answers2

0

Looks like you are stuck in that infinite for loop. Can you not do that, but just check the fileSize and dump strings once the file size is greater than fs?

David Neiss
  • 8,161
  • 2
  • 20
  • 21
  • The issue seems to be that that freopen() is like an atomic statement- it continues to write until the app terminates. I'm not sure how to halt freopen() when file size becomes greater than fs. – Apophenia Overload May 03 '11 at 21:34
  • Dont you just need to reopen the file once, to redirect to your log file? After that, in the NSLog, check the current file size. If its less than your threshold, write the data. If not, just exit the function. – David Neiss May 03 '11 at 21:55
0

Your code says:

As long as [fielAttributes fileSize] is less than fs, keep calling freopen(...).

Is that really what you want? I'd guess that you might prefer something like:

if ([fileAttributes fileSize] < fs) {
    file = freopen([FILEPATH cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
}
fwrite(file, "something to log");
fclose(file);

Of course, that's not great either, because it writes log information for fs characters and then stops. Instead, it seems like you probably want to preserve the LAST fs characters. If that's the case, then a pragmatic approach would be to simply copy the last fs characters to a new file and delete the old one from time to time.

Caleb
  • 124,013
  • 19
  • 183
  • 272