The IOUtil structure
Author: John Reppy
Keywords: Standard ML, SML, SML/NJ Library

The SML of NJ Library
The `IOUtil` structure

The `IOUtil` structure provides support for redirecting the standard input and output streams.

## Synopsis

    signature IO_UTIL
    structure IOUtil : IO_UTIL

## Interface

    val withInputFile : string * ('a -> 'b) -> 'a -> 'b
    val withInstream : TextIO.instream * ('a -> 'b) -> 'a -> 'b

    val withOutputFile : string * ('a -> 'b) -> 'a -> 'b
    val withOutstream : TextIO.outstream * ('a -> 'b) -> 'a -> 'b

## Description

`val withInputFile : string * ('a -> 'b) -> 'a -> 'b`

  `withInputFile (file, f) x` evaluates the expression `f x` with standard input bound to `file`. The file is closed and the `TextIO.stdIn` input stream is restored to its original binding once evaluation terminates.

`val withInstream : TextIO.instream * ('a -> 'b) -> 'a -> 'b`

  `withInstream (inS, f) x` evaluates the expression `f x` with standard output redirected to `inS`. The `TextIO.stdIn` input stream is restored to its original binding once evaluation terminates.

`val withOutputFile : string * ('a -> 'b) -> 'a -> 'b`

  `withOutputFile (file, f) x` evaluates the expression `f x` with standard output redirected to `file`. The file is closed and the `TextIO.stdOut` output stream is restored to its original destination once evaluation terminates.

`val withOutstream : TextIO.outstream * ('a -> 'b) -> 'a -> 'b`

  `withOutstream (outS, f) x` evaluates the expression `f x` with standard output redirected to `outS`. The `TextIO.stdOut` output stream is restored to its original destination once evaluation terminates.

## Example

The following expression will put its output in the file "hello.txt":

    withOutputFile ("hello.txt", fn () => print "hello world\n") ()

## See Also

The Util Library

SML/NJ Version 110.99.9 (November 4, 2025)
Last updated 2025-11-04 15:48:25 UTC