Written file only appears on the second run

I can’t figure this out and I can’t find a reference to this problem anywhere.

If I run my script and watch the Event Log, everything succeeds, including writing the file to disk. There are no errors, and everything looks good. However, there is no file on the disk where the script claims to have written the file after closing the file reference. If I do nothing, except run the script a second time, the file shows up. Stranger still, if I delete the file created by the script and run it a third time, the file is successfully created again.

So it appears to only fail to make the file appear on disk the very first time I run it.

I’m only passing a string to Apple’s write_to_file routine from here.

I have some experience with AppleScript’s problems with FileVault. My script is being run from a FileVault volume, but the file is being written to the startup disk outside of the FileVault, so that shouldn’t be it. I’m also running 10.4.5.

Has anyone encountered a similar problem? Any advice would be appreciated.


set fileName to "testfile"
set fileContents to ("I'm a test") as string

set filepath to (POSIX path of (("/Scratch/" & fileName & ".txt") as text))

set completed to my write_to_file(fileContents, filepath, false)

if not completed then
	display dialog "There was an error saving the selection." buttons {"OK"} default button "OK"
end if

on write_to_file(this_data, target_file, append_data)
	try
		set the target_file to the target_file as text
		set the open_target_file to ¬
			open for access file target_file with write permission
		if append_data is false then ¬
			set eof of the open_target_file to 0
		write this_data to the open_target_file starting at eof
		close access the open_target_file
		return true
	on error
		try
			close access file target_file
		end try
		return false
	end try
end write_to_file

This is the event log from a first-time run after which no file appears on the disk:
tell current application
open for access file “/Scratch/testfile.txt” with write permission
99
set eof 99 to 0
write “I’m a test” to 99 starting at eof
close access 99
end tell

The problem is this line:
set filepath to (POSIX path of ((“/Scratch/” & fileName & “.txt”) as text))

Apparently, the first time the script is run, a file is created in the root of the startup disk with this name:
/Scratch/testfile.txt (thats the name it appears to have in the Finder)
From the terminal, an ls reveals the file’s filename is
:Scratch:testfile.txt
I didn’t even realize that “/” or ":"were valid file name characters, but there they are.

If I change the above line to:
set filepath to POSIX file of (“/Scratch/” & fileName & “.txt”)

AppleScript errors out with this error:
Can’t get POSIX file “/Scratch/testfile.txt”.

Fixed it. The line should have read:
set filepath to (“/Scratch/” & fileName & “.txt”) as POSIX file