James
James

Reputation: 1289

How to write to a file in sml

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.

Upvotes: 3

Views: 4190

Answers (2)

sshine
sshine

Reputation: 16105

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

Upvotes: 2

John Coleman
John Coleman

Reputation: 51998

You're almost there. Between the in and end you need to delimit the expressions by the semicolon. In SML ; is a sequence-operator. It evaluates expressions in turn and then only returns the value of the last one.

If you already have an outstream open, use:

fun printToOutStream outstream str = let val os = outstream
                                     in
                                       TextIO.output(os,str);
                                       TextIO.closeOut os
                                     end;

Used like thus:

- val os = TextIO.openOut "C:/programs/testfile.txt";
val os = - : TextIO.outstream
- printToOutStream os "Hello SML IO";
val it = () : unit

Then when I go to "C:/programs" I see a brand new text file that looks like this:

enter image description here

Upvotes: 3

Related Questions