Reputation: 610
how exactly does one output the characters in a file to stdin in SML/NJ? Here is what i have so far but i'm currently stuck as i'm getting errors thrown back at me from the compiler.
Code:
fun outputFile infile =
let
val ins = TextIO.openIn infile;
fun helper copt =
case copt of
NONE = TextIO.closeIn ins;
| SOME(c) = TextIO.output1(stdIn,c);
helper(TextIO.input1 ins));
in
helper ins
end;
Any thoughts as to where I'm going wrong?
Upvotes: 1
Views: 328
Reputation: 1601
Well, it depends on what you are trying to do with the file input. If you just want to print the characters that are read from your file, without outputting it to another file, then you can just print the output:
fun outputFile infile = let
val ins = TextIO.openIn infile;
fun helper copt = (case copt of NONE => TextIO.closeIn ins
| SOME c => print (str c); helper (TextIO.input1 ins));
in
helper (TextIO.input1 ins)
end;
outputFile "outtest"; (*If the name of your file is "outtest" then call this way*)
However, that above example is bad, since it will give you infinite loop, as even when it hits NONE, does not know how to terminate and close the file. Therefore, this version is cleaner, more readable, and terminates:
fun outputFile infile = let
val ins = TextIO.openIn infile;
fun helper NONE = TextIO.closeIn ins
| helper (SOME c) = (print (str c); helper (TextIO.input1 ins));
in
helper (TextIO.input1 ins)
end;
outputFile "outtest";
If you just want to output the contents of your infile
to another file, then that's another story and you have to open up a file handle for output in that case.
Upvotes: 2