问题
Below is a simple program to write an int list to a file:
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;
Why no new line was written to file after each number printed?
回答1:
It appears that your code works and that a newline character is written after each number.
I have provided an alternative definition for your write
function, but both appear to work.
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")
来源:https://stackoverflow.com/questions/33618000/sml-why-no-new-line-cant-be-written-to-file-with-n