2014-02-27 49 views
0

我在SML中玩弄了一些输入/输出函数,并且我想知道是否可以将特定内容从一个文件复制到另一个文件,而不是复制整个文件?在SML中使用输入/输出

说,我有一个函数返回一个整数列表的文本文件中的一个,我只是想这样的结果列表复制到空的输出文件。如果这是可能的,我怎样才能将我的copyFile函数自动复制到输出文件?

下面是我使用的整个文本复制从一个文件到另一个功能:

所有的
fun copyFile(infile: string, outfile: string) = 
    let 
    val In = TextIO.openIn infile 
    val Out = TextIO.openOut outfile 
    fun helper(copt: char option) = 
     case copt of 
      NONE => (TextIO.closeIn In; TextIO.closeOut Out) 
     | SOME(c) => (TextIO.output1(Out,c); helper(TextIO.input1 In)) 
    in 
    helper(TextIO.input1 In) 
    end 

回答

1

首先,你的函数看起来相当低效的,因为它复制单个字符。为什么不简单地这样做:

fun copyFile(infile : string, outfile : string) = 
    let 
     val ins = TextIO.openIn infile 
     val outs = TextIO.openOut outfile 
    in 
     TextIO.output(outs, TextIO.inputAll ins); 
     TextIO.closeIn ins; TextIO.closOut outs 
    end 

此外,您可能想确保在发生错误时关闭文件。

在任何情况下,要回答你真正的问题:看来你是寻求某种形式的搜索功能,它允许你开始阅读之前向前跳转到特定的文件偏移。不幸的是,这样的功能在SML库中不容易获得(主要是因为它通常对文本流没有意义)。但是你应该能够实现它的二进制文件,见my answer here。就这样,你可以写

fun copyFile(infile, offset, length, outfile) = 
    let 
     val ins = BinIO.openIn infile 
     val outs = BinIO.openOut outfile 
    in 
     seekIn(ins, offset); 
     BinIO.output(outs, BinIO.inputN(ins, length)); 
     BinIO.closeIn ins; BinIO.closOut outs 
    end