To delete few lines and add few lines at the end of a text file using c program

M

Murali

Hello Everyone,


I am breaking my head with this problem. Please help
me out. Let me first explain my problem :

Here it is:

I am working in realtime environment where i will be creating
logfiles internally while my system is running.
I am having a logfile.txt in which i have to store maximum of 150
lines.Suppose for every 60 seconds 50 lines are going to add to my
logfile If it exceeds more than 150 my program should remove first 50
lines and add coming 50 lines at the end.

In brief to say how to delete few lines at the top of a text file and
append it 50 lines at bottom.


It will be very helpful for me if you send me any system call to solve
my problem or the code.

Thank you,
Murali
 
B

Ben Pope

Murali said:
In brief to say how to delete few lines at the top of a text file and
append it 50 lines at bottom.

You'll have to rewrite the entire file.

The general form is:
Read in old file, modify, write temporary file
Delete old file
Rename temporary file to old file name.

Ben Pope
 
J

Jerry Coffin

Hello Everyone,


I am breaking my head with this problem. Please help
me out. Let me first explain my problem :

Here it is:

I am working in realtime environment where i will be creating
logfiles internally while my system is running.
I am having a logfile.txt in which i have to store maximum of 150
lines.Suppose for every 60 seconds 50 lines are going to add to my
logfile If it exceeds more than 150 my program should remove first 50
lines and add coming 50 lines at the end.

As stated, this simply isn't possible (at least not
portably).

Your choices are 1) create something more or less along
the lines of a database, or 2) create the file anew each
time it's needed.

Given the size of file, the latter is probably the better
option in this case unless your lines are _really_ long.
With typical log file entries, you're looking at 150x40
(average) => around 6K. That just doesn't justify the
overhead of a database style of format (which wouldn't be
readable as normal text anyway).

If you have some memory available, I'd consider reading
the data in at startup, holding it in a circular buffer
in memory, and writing it out as needed. This way you're
not reading the old file back into memory on a regular
basis, cutting your I/O roughly in half.

If the log file is really crucial, instead of overwriting
the old log file, you're probably better off writing the
data to a new file, then deleting the old file and
renaming the new file to the old name.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top