如何写入sml文件

How to write to a file in sml

我正在尝试将字符串写入文件,但我似乎无法让它工作,虽然我已经阅读了关于堆栈溢出的所有此类问题,但 none 似乎正在解决问题。我来自命令式背景,所以通常我会写入文件,然后关闭输出流...但是这在 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.

我知道我需要写入文件并关闭输出流,但我不知道该怎么做。使用我的 "sml brain" 我告诉自己我需要调用函数递归地走向某事,然后当我到达它时关闭输出流......但我再次不知道我将如何做到这一点。

你快到了。在 inend 之间,您需要用分号分隔表达式。在 SML 中 ; 是一个序列运算符。它依次计算表达式,然后仅 returns 最后一个的值。

如果您已经打开了外流,请使用:

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

这样使用:

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

然后当我转到 "C:/programs" 时,我看到一个全新的文本文件,如下所示:

如果您总是read/write一次完成文件,您可以为此创建一些辅助函数,例如:

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