0
votes

I'm playing around with some Input/Output functions in SML, and I'm wondering if it's possible to copy specific content from one file to another, instead of copying the whole thing?

Say that I have a function in one of the text files that returns a list of integers, and I just want to copy this result list into the empty output file. And if this is possible, how can I apply my copyFile function to copy the list automaticly to the output file?

Here's the function I'm using for copy the whole text from one file to another:

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

1 Answers

1
votes

First of all, your function looks rather inefficient, since it's copying individual characters. Why not simply do:

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

Also, you may want to make sure to close the files in case of errors.

In any case, to answer your real question: it seems you are asking for some kind of seek function, that allows you to jump forward to a specific offset in a file before starting to read. Unfortunately, such a function is not readily available in the SML library (primarily, because it does not generally make sense on text streams). But you should be able to implement it for binary files, see my answer here. With that, you could write

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