如何逐行读取SML中的文件

问题描述

我想写一个逐行读取文本文件函数。即,读取第一行直到 EOL,然后将其视为字符串,并重复此操作直到文本结束。 到目前为止,我只管理了这么多:

fun read file = 
let val is = TextIO.openIn file
in
end

解决方法

您可以为此使用 TextIO.inputLine : instream -> string option。使用 ref 可以做类似

let
  val is = TextIO.openIn file
  val done = ref false
in
  while not (!done) do
    case TextIO.inputLine of
      SOME s => print s
    | NONE => done := true
end

您也可以使用 TextIO.StreamIO 中的函数。