为 freopen() 和 stderr 提供缓冲区(限制 iOS 应用程序日志文件的大小)

发布于 2024-11-05 01:39:58 字数 351 浏览 2 评论 0原文

我目前正在使用应用程序委托调用 freopen() 将 NSLog() 输出重定向到文件。我想限制日志文件大小,但这样做

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

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

  }

会导致应用程序陷入无限循环中的黑屏。有什么方法可以为 stderr 设置缓冲区大小,然后有一个循环,其中只有在文件大小 + 缓冲区大小不超过文件大小时才继续写入文件?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

懵少女 2024-11-12 01:39:58

看起来你陷入了无限循环。您可以不这样做,而是在文件大小大于 fs 时检查 fileSize 并转储字符串吗?

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?

只有影子陪我不离不弃 2024-11-12 01:39:58

你的代码说:

只要[fielAttributes fileSize]
小于fs,继续调用
freopen(...)。

这真的是你想要的吗?我猜你可能更喜欢这样的东西:

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

当然,这也不是很好,因为它为 fs 字符写入日志信息,然后停止。相反,您似乎可能想保留最后的 fs 字符。如果是这种情况,那么一种实用的方法就是简单地将最后的 fs 字符复制到新文件中,并时不时地删除旧文件。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文