【问题标题】:Using Input/Output in SML在 SML 中使用输入/输出
【发布时间】:2014-02-28 18:12:46
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: io sml


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-05
      • 2015-07-25
      • 2016-07-12
      • 2018-02-21
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多