[Closed] Saving/Reading string to/from text files
Hi,
So usually I use two functions like that to save to / read from file.
fn readFrom = (
file = "C:\ mp\\readThis.txt"
fs = openFile file
arr = #()
while eof fs != true do (
itm = (readLine fs)
append arr itm
)
close fs
arr
)
fn writeTo THIS = (
file = "C:\ mp\\readThis.txt"
deleteFile file
ss = createFile file
print THIS to:ss
close ss
)
And I use it to save/load numbers and strings. But it does not work for strings that well. So lets say I created this file (“C:\ mp\readThis.txt”) manually and input “TESTING”, but without quatmarks, so its just TESTING.
When now I read this file I get what I want, which is a string “TESTING”. Thats all well.
But now I want to write something else into the file. So lets say I use my writeTo() function now:
writeTo "CallmeCrazy"
And if I read the file again I get ““CallmeCrazy””. And thats not I want. Is there any way to make it not double quatmarks?
I fixed that like that:
while eof fs != true do (
itm = (readLine fs)
newArr = filterString itm "\""
itmOut = ""
for obj in newArr do (
itmOut += obj
)
append arr itmOut
)
Its working. But maybe there is some other way, to fix it on the write moment?
Here are two simple functions to read/write numbers and strings. Note that numbers are saved without quotes and strings are saved with quotes. For example:
123
“TESTING”
(
fn ReadFromFile filename =
(
if doesfileexist filename do
(
stream = openfile filename
result = #()
while not eof stream do append result (readvalue stream)
close stream
)
return result
)
fn WriteToFile filename val add:true =
(
mode = case add of
(
true: "at"
false: "wt"
)
stream = openfile filename mode:mode
print val to:stream
close stream
)
/* TEST ------------------- */
file = "C:\\readThis.txt"
WriteToFile file 0.1
WriteToFile file 2
WriteToFile file "TESTING"
ReadFromFile file
)
If you want to save the values (numbers and strings) without quotes, you can use format() instead of print(), but then using readLine() numbers will be read as strings so you would need to implement a better parsing.
123
TESTING
(
fn ReadFromFile filename =
(
if doesfileexist filename then
(
stream = openfile filename
result = #()
while not eof stream do append result (readline stream)
close stream
)
return result
)
fn WriteToFile filename val add:true =
(
mode = case add of
(
true: "at"
false: "wt"
)
stream = openfile filename mode:mode
format "%
" val to:stream
close stream
)
/* TEST ------------------- */
file = "C:\\readThis.txt"
WriteToFile file 0.1
WriteToFile file 2
WriteToFile file "TESTING"
ReadFromFile file
)