I have a script that writes a number to a text file, then the next time it runs reads that number and does some math to it. I seeded the text file the first time the script run with a number and it worked ok. On the second time I get an error saying it can not turn the text into a number. In the event log i get this:
write “880” to 277
close access 277
“Can’t make "875" into a number.”
Any suggestions on whats causing this?
Thanks!
-Adam
Hard to say exactly without seeing the code, Adam.
However, I can show you an example that works here, and which is based loosely on your description:
set f to (path to "desk" as Unicode text) & "test file"
set d to open for access file f with write permission
if (get eof d) is 0 then
set n to 880
else
set n to read d
set n to n - 5
set eof d to 0
end if
write n to d as string
close access d
n
If it works for you, see if you can work out what’s fundamentally different in your script. If you’re still stuck, then perhaps you could give us more clues, by posting the relevant code you’re using…
set movnum to (read file “Macintosh HD:Users:adam:desktop:tovid.txt”)
set figut to text returned of (display dialog “What is the last file number?” default answer “”)
set fileRef to (open for access file “Macintosh HD:Users:adam:desktop:tovid.txt” with write permission)
set eof of fileRef to 0
write figut to fileRef
close access fileRef
set lastnum to (figut - movnum) + 1
Strangely enough, Adam, your code works fine here. My machine’s obviously more tolerant (it needs to be), since it automatically coerces the strings to numbers in order to perform the calculation.
It’s sometimes possible to force a coercion by putting the number before the strings:
set lastnum to 1 + figut - movnum
In fact, both ‘figut’ and ‘movnum’ are strings, so you need to test what works best. To be absolutely safe, you could explicitly coerce both strings before performing the math:
set lastnum to 1 + (figut as number) - (movnum as number)
Incidentally, it might be more efficient to refer to the file only once in the routine:
set figut to text returned of (display dialog "What is the last file number?" default answer "")
set fileRef to (open for access file "Macintosh HD:Users:adam:desktop:tovid.txt" with write permission)
set movnum to read fileRef
set eof fileRef to 0
write figut to fileRef
close access fileRef
set lastnum to 1 + (figut as number) - (movnum as number)
Oh yeah - one query: I take it there’s a reason for not using properties…
property movnum : 1 -- or whatever the start number is
set figut to text returned of (display dialog "What is the last file number?" default answer "") as number
set lastnum to 1 + figut - movnum
set movnum to figut
lastnum