SML:为什么没有新行不能写入带有“\ n”的文件? [英] SML: Why no new line can't be written to file with "\n"

查看:130
本文介绍了SML:为什么没有新行不能写入带有“\ n”的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个将int列表写入文件的简单程序:

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?

推荐答案

看来您的代码有效,每个数字后面都会写一个换行符。

It appears that your code works and that a newline character is written after each number.

I为您的函数提供了另一种定义,但两者似乎都有效。

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")

这篇关于SML:为什么没有新行不能写入带有“\ n”的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆