tags:

views:

174

answers:

1

I need to write some system log data (usually not more than 100 characters at a time) into a log file based on particular events. But the size of this log file is small (say around 4KB), and I need to wrap around the logs when the file size hits the limit. While wrapping around, I need to preserve the latest info, and later on present it in chronological order as it was written to the file. What is the best way to do this? I want to avoid making copies of the file to do this.

+6  A: 

To write to a restricted file:

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

To meet your modified requirements, you will need to use a record-based file. Choose arecord size slightly bigger than the largest message and give each message a timestamp. The algorithm I described still works, except that you go back to the start if you can't write the whole message. You will also need to write a small application to read the file and present the contents in chronological order.

Alternatively, investigate using an existing logging library like log4c.

anon
I was under the impression that ftell return value might not be the exact number of bytes from the beginning of the file.
Thomas Owens
It will be if you open the file in binary mode.
anon
@Neil: I heard somewhere that most modern operating systems ignore the "b" flag when opening files and open them in binary mode anyway, but now that I try and find out about the validity of this claim, nothing seems to pop up. Do you know if it is true?
dreamlax
The operating system has no such concept as "binary mode" - the differences between this and "text mode" are entiirely handled by the C runtime library.
anon
+1 Go get that 20k :)
Magnus Skog
Sincere apologies for not being very clear earlier with my query
Harty