Reading/Deleting Last Line Of File

Alex Tweedly alex at tweedly.net
Thu Feb 11 17:49:02 CST 2010


Jeff Massung wrote:
> Warren,
>
> I've read through most of these suggestions, but I'm surprised that the
> obvious hasn't been suggested yet (that I've seen): skip everything...
>
>   
Hasn't been suggested because it won't work.

> put the length of url "file:myfile.txt" into tEnd
> open file "myfile.txt" for text update
> seek to tEnd in file "myfile.txt"
>
> >From here just back up a "reasonable" number of characters... say 200. Find
> the last CR character, nuke everything else and close the file. Didn't find
> one? Try backing up another 200, etc. It'll be a whole lot faster.
>
>   
"... nuke everything else ...." ?? How ?
You've opened the file for update, so anything that you write to the 
file *overwrites* any existing characters at the same position(s), and 
leaves everything following that unchanged. So there is no way to 
shorten a file if opened in update mode.

I *think* the best you can do is

1. find file length (best to use the detailed files)
2. open for read, and read some chunk at the end (200, 1000, whatever ....)
       (open for read is more efficient than open for update)
3. calculate the number of bytes to be deleted off the end of the file
4. close the file
5. open the file for append
6. write empty to the file at the appropriate point
> Edge case to concern yourself with would be if your file happens to end with
> a CR and maybe you want to ignore those cases. But that should be easy
> enough to solve.
>
>   
Easiest (and I think best) way to resolve that corner case is to 
preserve the trailing CR if it's there to begin with, and not leave one 
if it wasn't there to start with. This happens to involve no extra work 
at all, hence it's the easiest one :-)

I decided it was time to email some (reasonably tested) revTalk rather 
than just ideas ....

(NB assumes that the defaultfolder has already been set to the 
appropriate place)
> on deletelastline pFile
>    constant K = 1000
>    put the detailed files into t
>    filter t with pFile & ",*"
>    put item 2 of t into tFileLength
>    
>    open file pFile for read
>    seek to tFileLength-K in  file pFile
>    read from file pFile until end
>    close file pFile
>    
>    put the number of chars in the last line of it into tNum
>    
>    open file pFile for append
>    write empty to file pFile at (tFileLength-tNum-3)
>    close file pFile
>    
>    end deletelastline
-- Alex.



More information about the use-livecode mailing list