2013-04-09 134 views
1

如何输出文件中的字符到SML/NJ中的标准输入?这是我迄今为止,但我目前卡住,因为我得到的错误从编译器扔回给我。输出文件到标准输入

代码:

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; 

任何想法,以我要去哪里错了吗?

回答

2

那么,这取决于你要用文件输入做什么。如果你只是想打印从您的文件中读取字符,而无需将其输出到另一个文件,那么你可以只打印输出:

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

然而,上面的例子是不好的,因为它会给你无限循环,因为即使遇到NONE,也不知道如何终止和关闭文件。因此,这个版本是更清洁,更具可读性,并终止:

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

如果你只是想输出你infile的内容复制到另一个文件中,则是另一回事,你必须打开输出文件句柄在这种情况下。

相关问题