I'm trying to write a string to a file, however I cant seem to get it working, I've read though all the questions like this on stack overflow but none seem to be addressing the issue. I'm from an imperative background so usually I would, write to file, then close the output stream... However this doest work in sml.
fun printToFile pathOfFile str = printToOutstream (TextIO.openOut pathOfFile) str;
//Here is where the issues start coming in
fun printToOutStream outstream str = TextIO.output (outstream, str)
TextIO.closeOut outstream
//will not work. I've also tried
fun printToOutStream outstream str = let val os = outStream
in
TextIO.output(os,str)
TextIO.closeOut os
end;
//also wont work.
I know I need to write to the file and close the output stream but I cant figure out how to do it. Using my "sml brain" I'm telling myself I need to call the function recursively stepping towards something and then when I reach it close the output stream... but again I don't have a clue how I would do this.
If you always read/write complete files at once, you could create some helper functions for this, like:
fun readFile filename =
let val fd = TextIO.openIn filename
val content = TextIO.inputAll fd handle e => (TextIO.closeIn fd; raise e)
val _ = TextIO.closeIn fd
in content end
fun writeFile filename content =
let val fd = TextIO.openOut filename
val _ = TextIO.output (fd, content) handle e => (TextIO.closeOut fd; raise e)
val _ = TextIO.closeOut fd
in () end