Search code examples
smlsmlnj

How to read a file in SML line by line


I want to write a function that reads a text file line by line. ie, read the first line until EOL and then treat this as a string, and repeat this until the text ends. I have managed only this much till now:

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

Solution

  • You can use TextIO.inputLine : instream -> string option for this. Using refs you can do something like

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

    You can also use the functions in TextIO.StreamIO.