Read/Write to file Problem

Hi Folks,

I am playing with the “writing/reading” from/to File:


property sent_file : true
property received_file: true


-- defining the files

set sent_file to (((path to me as Unicode text)as string) & "Contents:Resources:sent.txt") as file specification
set received_file to (((path to me as Unicode text) as string) & "Contents:Resources:received.txt") as file specificationtr

-- reading from file:

set received_data to read received_file as string
--display dialog received_data is showing 0 but in the file there is 122
set sent_data to read sent_file as string

-- writing to file:

set sent_final to "123444"
try
open for access sent_file with write permission
set eof of sent file to 0
write (sent_final) to sent_file starting at eof
close access sent file
end try


Everything is working fine, but where the heck will the data be written, because in my files there are no entries… :slight_smile:

Thanks for any suggestions,

Stefan

Hi Stefan,

I’d like to recommend you two books about AppleScript:
Matt Neuburg - AppleScript The Definitve Guide (in my opinion the bible of AS)
Hanaan Rosenthal - AppleScript A Comprehensive Guide

You are very engaged in scripting and with these books you can learn it from scratch

Here is a universal write_to_file subroutine:

on write_to_file(|data|, target, append)
	try
		set open_target_file to open for access file target with write permission
		if append is false then set eof of open_target_file to 0
		write |data| to open_target_file starting at eof
		close access open_target_file
		return true
	on error
		try
			close access file target
		end try
		return false
	end try
end write_to_file

Stefan’s handler is the way to go with one caveat. Target cannot be an alias unless the target file already exists.

Hi Stefan, Hi Adamn,

I have received Hanaan´s Book some weeks ago and it is really helpful,
but sometimes there are things which I am not really understanding…

one thing I am not able to understand is the thing with writing to file/reading to file

I am writting or reading to some file, but not to the one which I have scripted…

That means, that I can read or write the correct data, but I am not sure, or I am not able to
find the file the programm is writing too…

This is very confusing…

Thanks for your continous help!

Stefan

If you are running the script you show first from the Script Editor or Script Debugger 4, path to me is path to SE or SD4, not to the script. See if your text file is in the Resources folder of the editor you’re using.