I’ve tried rewriting text files using the write command, but when I write shorter files, the old file is still “hanging” off the end. I’ve tried setting the EOF to the length of the new (shorter) file, but it doesn’t seem to work either, probably because length counts characters, not unicode bytes.
If you set the eof of theFile to 0, before you write to it, it completely erases the file, Kevin, and substitutes the new text. See Nigel Garvey’s article on the Ins & Outs of File Read/Write for the last word.
Thanks Adam. That’s essentially the same conclusion I came to, I just thought there was another (documented) way of doing it that wasn’t apparent to me.
FWIW - shouldn’t the “unadorned” write command work that way anyway? Since the starting at and for parameters exist, one would think that those would handle file appends and such. When doing (any) write to a file, even if you are in a repeat loop you would think eof would be set to the end of the last (previous) write, not the old eof of the file.
The starting at and for parameters allow you do do an insertion in the text that exists, but eof defines where a read without them should stop. That’s at the end of the content unless you move it and if you move it, you lose anything after it. If that weren’t the case, you’d fill up the file with unreadable “old” text that you could only purge by moving the eof again.
I guess my point was, if I write For what it’s worth to a file and close it, then come along later and write Foo it wouldn’t occur to me to assume that the result would be Foo what it’s worth. And in practical application, I can’t imagine any time where I would WANT the old text to remain. It just seemed that most people would assume that any read operation would stop where the previous write stopped.
Anyway, it all works, and that’s what is important!
Just to make sure it’s clear to other readers, Kevin:
set tFile to (path to desktop folder as text) & "Trial.txt"
set f to open for access tFile with write permission
try
set eof of f to 0 -- start from scratch. 'starting at 0' just overwrites what was there before.
write "Now is the time" to f
close access f
on error
close access f -- insurance
end try
display dialog (read file tFile) --> Now is the time
--- Some time later, perhaps, we return....
set g to open for access tFile with write permission -- g different from f (which expired with "close")
try
write return & "for all good men" to g starting at eof -- add to what's already there.
close access g
on error
close access g
end try
display dialog (read file tFile)
--> Now is the time
--> for all good men