2 * Safe(r) I/O functions
3 * Author: Frank Pfenning <fp@cs.cmu.edu>
8 (* withOpenIn fileName (fn instream => body) = result
9 opens fileName for input to obtain instream and evaluates body.
10 The file is closed during normal and abnormal exit of body.
12 val withOpenIn : string -> (TextIO.instream -> 'a) -> 'a
14 (* withOpenOut fileName (fn outstream => body) = result
15 opens fileName for output to obtain outstream and evaluates body.
16 The file is closed during normal and abnormal exit of body.
18 val withOpenOut : string -> (TextIO.outstream -> 'a) -> 'a
21 structure SafeIO :> SAFE_IO =
24 (* result of a computation *)
25 datatype 'a Result = Value of 'a | Exception of exn
28 (* withOpenIn fileName (fn instream => body) = result
29 opens fileName for input to obtain instream and evaluates body.
30 The file is closed during normal and abnormal exit of body.
32 fun withOpenIn (fileName) (scope) =
34 val instream = TextIO.openIn fileName
35 (* val _ = fileOpenMsg (fileName) *)
36 val result = Value (scope instream) handle exn => Exception (exn)
37 (* val _ = fileCloseMsg (fileName) *)
38 val _ = TextIO.closeIn instream
42 | Exception (exn) => raise exn
45 (* withOpenOut fileName (fn outstream => body) = result
46 opens fileName for input to obtain outstream and evaluates body.
47 The file is closed during normal and abnormal exit of body.
49 fun withOpenOut (fileName) (scope) =
51 val outstream = TextIO.openOut fileName
52 (* val _ = fileOpenMsg (fileName) *)
53 val result = Value (scope outstream) handle exn => Exception (exn)
54 (* val _ = fileCloseMsg (fileName) *)
55 val _ = TextIO.closeOut outstream
59 | Exception (exn) => raise exn