下面是一个将int列表写入文件的简单程序:
fun write(num_list, file) =
let
val output = TextIO.openOut file
fun num(nil) = TextIO.closeOut output
| num(n::ns) = (TextIO.output(output, Int.toString(n)); TextIO.output(output, "\n"); num(ns))
in
num(num_list)
end;
为什么在打印每个数字后没有新行写入文件?
答案 0 :(得分:0)
您的代码似乎有效,并且每个数字后面都会写一个换行符。
我为您的write
功能提供了另一种定义,但两者似乎都有效。
fun writeInts (ints, filename) =
let val fd = TextIO.openOut filename
val _ = List.app (fn i => TextIO.output (fd, Int.toString i ^ "\n")) ints
val _ = TextIO.closeOut fd
in () end
fun read filename =
let val fd = TextIO.openIn filename
val content = TextIO.inputAll fd
val _ = TextIO.closeIn fd
in content end
val test = (writeInts ([1,2,3,4], "hello.txt"); read "hello.txt" = "1\n2\n3\n4\n")