Page 1 of 1
Creating a text file from livecode
Posted: Fri Sep 19, 2014 5:37 am
by monki
I know it's possible to read from, and write to, existing text files, but is it possible to take text from a field and use it to create a new text file? If not, could a standalone stack copy an existing text file to the save location and write to that? Would that be the way to create a "new" file?
Re: Creating a text file from livecode
Posted: Fri Sep 19, 2014 5:46 am
by Simon
Hi monki,
Easy peasy!
put fld "myText" into url "file:myNewFile.txt"
Now that will put it in the current default directory.
Simon
Re: Creating a text file from livecode
Posted: Fri Sep 19, 2014 6:33 am
by monki
I never would've thought of "URL". Saw it in the user doc, but thought it only pertained to servers

Anyway, that got it working, thanks
Re: Creating a text file from livecode
Posted: Fri Sep 19, 2014 3:03 pm
by FourthWorld
In addition to the URL syntax, you can also work with files using open, write/read, and close, e.g.:
Code: Select all
on SaveFile pData, pFile
open file pFile for write
if the result is not empty then
answer "Couldn't create file ""e& pFile "e& "(" & sysError() &")"
exit to top
end if
write pData to file pFile
close file pFile
end SaveFile
Re: Creating a text file from livecode
Posted: Fri Sep 19, 2014 4:15 pm
by monki
So, opening, and writing to, a non-existing text file will create a new file?
I actually tried the open, write, close thing for creating files first and it didn't work. Maybe I got some of the syntax wrong.
Re: Creating a text file from livecode
Posted: Fri Sep 19, 2014 5:34 pm
by FourthWorld
See the error handling block in the example I posted. Many times the issue is an invalid file path, or incorrect permissions for the destination folder. Checking the result will let you know if something went wrong, and using sysError() will provide the OS code related to the issue.