Simple way to write to a txt file?

Hi! I’m trying to write some strings from my app to a simple txt file, making a kind of log file of what my app is doing, for debug purpose.
I’d like to make a simple function to write one line after every executed instructions.
The problem is I cannot write to a file. I know maybe is a stupid question but I didn’t find an answer.
I find somewhere here in the forum this kind of function:

on write_message_(theActionExecuted)
set filePath to (path to desktop as string) & “debugLog.txt”
try
set fileRef to open for access file filePath with write permission
write theActionExecuted to fileRef theActionExecuted
close access fileRef
on error
try
close access file filePath
end try
end try
end write_message_

But this doesn’t work. Do you know for any problem with write function on ASOC?
I saw also the function “writeToFile_atomically_” but I don’t’ understand how to use it?
Any better simple way to write to txt file?
Thank you in advance.
Rex

Hi,

the code is quite right


on write_message_(theActionExecuted)
	set filePath to (path to desktop as string) & "debugLog.txt"
	try
		set fileRef to open for access file filePath with write permission
		write (theActionExecuted & return) to fileRef starting at eof
		close access fileRef
	on error
		try
			close access file filePath
		end try
	end try
end write_message_


the ASOC version is a bit more complicated


on writeToLog_(theMessage)
	set theMessage to current application's NSString's stringWithFormat_("%@
", theMessage)
	set theMessageData to theMessage's dataUsingEncoding_(current application's NSUTF8StringEncoding)
	set logPath to POSIX path of (path to desktop) & "debugLog.txt"
	set fileManager to current application's NSFileManager's defaultManager()
	if not (fileManager's fileExistsAtPath_(logPath)) then
		set theResult to fileManager's createFileAtPath_contents_attributes_(logPath, theMessageData, missing value)
	else
		set logFileHandle to current application's NSFileHandle's fileHandleForWritingAtPath_(logPath)
		logFileHandle's seekToEndOfFile()
		logFileHandle's writeData_(theMessageData)
		logFileHandle's closeFile()
	end if
end writeToLog_

This line won’t work in ASObjC, as outlined here: www.macosxautomation.com/applescript/apps/gotchas.html

Change it to something like:

set fileRef to open for access current application's file filePath with write permission

Thank you very much. Both solutions work like a charm. Thank you very much.
:smiley:

HI Stefan,

Your code is very nice to learn from. Thanks
t.