2014-02-27 45 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