Page 1 of 1

writing and reading arrays to and from text files

Posted: Wed Jan 05, 2011 5:33 pm
by grimaldiface
I want to save the contents of an array to a text file so that I can retrieve the data later. I am using the "arrayEncode" and "arrayDecode" functions, first encoding the array, then writing it to a text file, then later reading from the text file and decoding it. However, I am running into problems when I read the encoded array from the text file. Essentially it comes out different than it went in so that I can't decode it. Here is an example of what I am trying to do......

Code: Select all

 
   --make array
   put "gel desk lamp window chair" into tlist
   repeat with x=1 to 5
      put word x of tlist into tarray[x]
   end repeat

   --encode and save array
   put arrayencode(tarray)into tvar
   put tvar into URL "file:testfile.txt"
   
   --load and decode array
   put empty into tarray
   put URL "file: testfile.txt" into tnewvar
   put arraydecode(tnewvar) into tarray
The weird thing is, the first time I encode the array and put it into "tempvar" in looks like this:
Picture 1.png
Picture 1.png (4.39 KiB) Viewed 3833 times
However, when I read it from the file, it comes out like this:
Picture 3.png
Picture 3.png (3.61 KiB) Viewed 3833 times
(^Those are screenshots from the variable viewer)
Something is lost in writing or reading to file. Any ideas what I am doing wrong?

Re: writing and reading arrays to and from text files

Posted: Wed Jan 05, 2011 5:54 pm
by FourthWorld
Instead of "file" use "binfile". The "file" token tells the engine to translate any platform-specific line endings to the Unix standard used internally (LF, or ASCII 10), which will likely cause corruption with binary data.

Re: writing and reading arrays to and from text files

Posted: Thu Jan 06, 2011 6:19 pm
by grimaldiface
Ah, this worked. Thanks, fourthworld!

Re: writing and reading arrays to and from text files

Posted: Mon Jan 10, 2011 9:13 am
by hliljegren
You can also add base64encode / decode to your conversion. Then you can safely save it to text file and also send it to a web server via http etc. I usually use:

Code: Select all

base64encode(compress(arrayEncode( tArray )))
to encode my arrays and safely save them to files / internet servers.

And then the reverse to decode:

Code: Select all

arrayDecode(decompress(base64Decode( textData )))