How do I get the file descriptor of a file opened using TextIO.openIn?

Viewed 56

In Standard ML, I have opened a file using TextIO.openIn "myfile.txt". This returns a value of type TextIO.instream. How do I get the POSIX file descriptor of type Posix.FileSys.file_desc from this instream?

1 Answers

Here's a function which does it, returning a Posix.FileSys.file_desc option.

fun instreamToPosixFD (ins: TextIO.instream) : Posix.FileSys.file_desc option =
  let
    val (TextPrimIO.RD reader, _) =
      TextIO.StreamIO.getReader (TextIO.getInstream ins)
  in
    case #ioDesc reader of
      NONE => NONE
    | SOME id => Posix.FileSys.iodToFD id
  end

The use of option for the output is consistent with the types in the Basis Library. As far as I can tell, if you open a file with TextIO.openIn and pass the result to this function, you will get a SOME result. My guess is that NONE is only possible for a TextIO.instream that is not backed by an open file.

Related