将数据写入C中的受限大小的文本文件

Har*_*rty 0 c file-io

我需要根据特定事件将一些系统日志数据(通常一次不超过100个字符)写入日志文件.但是这个日志文件的大小很小(比如大约4KB),当文件大小达到极限时我需要回滚日志.在环绕时,我需要保留最新的信息,然后在写入文件时按时间顺序显示它.做这个的最好方式是什么?我想避免复制文件来执行此操作.

小智 7

要写入受限文件:

call ftell to find out where you are in the file
call fwrite to write as much as you can, with respect to restricted size
if you couldn't write the whole message
  call fseek to return to the start of the file
  call fwrite to write the remainder of the message
Run Code Online (Sandbox Code Playgroud)

要满足修改后的要求,您需要使用基于记录的文件.选择比最大消息略大的arecord大小,并为每条消息添加时间戳.我描述的算法仍然有效,除非你不能写完整个消息就回到起点.您还需要编写一个小应用程序来读取文件并按时间顺序显示内容.

或者,使用现有的日志记录库(如log4c)进行调查.