Failing to delimit read file contents

Hello all, another question I’m hoping you can help me with. I’m trying to read my preferences file, and then use the ol’ Applescript text item delimiters to parse out the values I need. Unfortunately, when I run my parsing function, it works great when I supply hard-coded text, but when I pass in the results of my file read, it can’t find anything (it always delimits as one item, no matter what string I set as the delimiters). I’ve attached my parsing function and my file reading function.

As a separate bonus item, how do you write returns into string literals? If I were coding C, I would use “\n”, but I don’t think that works here (although I guess I haven’t actually tried it ;-)).

Thanks for your assistance!

-Joe


-- returns the entire contents of the file with the given path
on ReadFile(filePath)
	set fileRef to open for access filePath
	set fileContents to (read fileRef)
	close access fileRef
	return (fileContents as string)
end ReadFile

-- searches theString for the value inbetween the beforeText and afterText
on getValueBetween(beforeText, afterText, theString)
	set OldDelims to AppleScript's text item delimiters
	set AppleScript's text item delimiters to beforeText
	set textItems to text items of theString
	set AppleScript's text item delimiters to OldDelims
	if ((count of textItems) is 1) then return "" -- no beforeText
	set AppleScript's text item delimiters to afterText
	set textItems2 to text items of (second item of textItems)
	set AppleScript's text item delimiters to OldDelims
	if ((count of textItems2) is 1) then return "" -- no afterText after beforeText
	return (first item of textItems2)
end getValueBetween

Hi, Talix.

What’s in the file? Text? Unicode Text? Numbers?

The read command assumes that it’s reading plain text, unless told otherwise. If your file does contains plain text, your parsing handler should work just as well with it as with the hard-coded text you tried. If the file contains Unicode text, you’ll need to read it as Unicode text.

set fileContents to (read fileRef as Unicode text)

as is here an optional parameter of read. It’s not a coercion as such. It tells read how to interpret what’s in the file ” in this case, “read every two bytes as a Unicode character.”

Assuming there isn’t a need for something other than the standard preferences system, the user defaults system will take care of everything for you, both storage and retrieval.

big long URL

There are also a bunch of examples here in the archives. Search for “user defaults” to find 'em.

The file is plain text as far as I know (created via another 3-4 line function in my program), but I’ll try the unicode text trick to see if that’s it - maybe that’s a default that I’m not aware of. Regardless, though, I’ll also check out the built-in user default system mentioned - that seems like the more elegant solution anyway.

Thanks a lot for your help!

-Joe