March 18th, 2003, 02:17 AM
fprintf - file input
i know i'm really a beginner in ANSI C. I have to fill in a textfile with logs. The problem is that the last input is the last line in the textfile.
I want that the last input is the first line? How can I achieve this the easiest way? To read everything out and fill it in afterwards would be quite unefficient?
March 18th, 2003, 03:12 AM
As far as I know, you can only do two things when writing to a file: you can add to the end of the file, or you can overwrite something in the file.
March 18th, 2003, 03:29 AM
i know that i can only open files with serveral flags, which only allow appending info or deleting the file and inserting new info.
but i need a short algorithm which allows inserting lines at the beginning and doesn't delete the other lines.
thx in advance
March 18th, 2003, 05:15 AM
"To read everything out and fill it in afterwards would be quite unefficient?"
My point was, as far as I know, you don't have any other options.
It doesn't sound very hard. You could read the current lines of the file into strings, then write the current log to the file, and subsequently write the strings back to the file.
March 18th, 2003, 09:53 AM
Or another kludge would be:
1. create a new file.
2. write the new log entry to it. Keep the new file open.
3. open the log file for read.
4. read each line of the log file and write it to the new file.
5. close both files.
6. delete the log file
7. rename the new file to the log file's name.
Instead of deleting the log file, you could keep a series of backup copies just in case, similar to Linux's messages log files -- messages, messages.1, messages.2, messages.3, messages.4 etc.
In that case, steps 6 & 7 would be:
6. delete the oldest log-file back-up (eg, log.4)
7. rename the next-oldest to the oldest's name
8. similarly bump the names of the other log files:
log.2 -> log.3
log.1 -> log.2
log -> log.1
9. now rename the new file to the log-file name.
Not very elegant, but it should work.
March 18th, 2003, 11:19 AM
thanks for your advice.
was quite a help for me.