Reputation: 316
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.
Upvotes: 0
Views: 406
Reputation:
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.
Upvotes: 7