Re: Rewrite last line in text file
From: Perry Way (no.delphipro.spam_at_no.spam.earthlink.net)
Date: 10/16/03
- Next message: Perry Way: "Re: Reading and writing doubles"
- Previous message: Chris Cowley: "Reading and writing doubles"
- In reply to: Magnus Oskarsson: "Rewrite last line in text file"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 16 Oct 2003 09:10:03 -0700
"Magnus Oskarsson" wrote
> I have a (potentially large) text file where I sometimes want to write a
new
> line (at the end), and sometimes replace the last line with a new one (the
> new line is never shorter than the old one if that is of any help). Is
there
> an easy way to do the latter? Note: I do not want to have to rewrite the
> entire file each time or to have to parse the file from the beginning,
this
> must be efficient.
How's this for efficiency....?
Use a TFileStream to open the file. Set its position to the end of the file
minus a fixed block size (say, 1024 bytes). Read the block of bytes into a
buffer (I would use a PChar because you access it like an array and it is
dynamically sized). Now parse the buffer backwards, looking for the first
occurance of #13 (first as you're parsing but this would be the last #13 in
the file). If you don't find one, increment a counter of the bytes you're
reading in reverse and re-read another block of bytes into that buffer and
continue in that pattern until you reach the #13 character. Once you have
found the position of the last carraige return, set the position of the
TFileStream to that point (plus two bytes if you want to keep the old CR/LF)
start writing your replacement string. Once you start writing the stream
from that position, all the remaining bytes in the file are truncated, so in
effect all you need to do is position yourself where you want to "continue"
your file from and start writing from there.
Most of Delphi's more optimized string routines were made for working with
strings from left to right, not right to left. Since you're mentioning
efficiency is important I wouldn't seek any other alternative than this
idea. I don't think you're going to find a more efficient (and simple) way
juggling pieces of functionality from various components and applying hacks
to them.
If you need further help, just holler. I like teaching these kind of
things..
PW
- Next message: Perry Way: "Re: Reading and writing doubles"
- Previous message: Chris Cowley: "Reading and writing doubles"
- In reply to: Magnus Oskarsson: "Rewrite last line in text file"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|