How to read from a file in SML?
I am trying to read text from a file into SML, but I cannot get it to work. This is what I am trying
fun read file =
let val inStream = TextIO.openIn file
in
TextIO.StreamIO.input1 inStream
end
The actual function call is input1
not important, all I want is the ability to read from a file.
source to share
You are wrong in TextIO.StreamIO.input1
, you most likely mean TextIO.input1
.
If you really need / do not work with the file using StreamIO, you need to convert the type instream
that is returned openIN
in StreamIO.instream
a function TextIO.getInstream
.
You can learn more about this in the SML database library signature TEXT_IO .
Remember, it is good practice to close the files when you are finished reading them.
Update
As pointed out in the comments, you can either read through the entire file (if you know it is small) or you can read it line by line.
The easiest way to do it if you don't want the word to be contained in the word is to split the content by spaces. This way, you will get a list of lines, which are individual words from the file.
source to share