Version française
Home     About     Download     Resources     Contact us    
Browse thread
File I/O and Finalization
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: David McClain <dmcclain@a...>
Subject: File I/O and Finalization
Finalization is not really required here... I have implemented a very simple
version of the Lisp UNWIND-PROTECT mechanism to handle the automatic closing
of files:

let unwind_protect fn_do fn_exit =
  let rslt =
    try
      fn()
    with
 exn ->
   ignore(exitfn());
   raise exn
  in
    ignore(exitfn());
    rslt

then one can define a safe I/O operation on files as:

let with_file filename fn =
  let fp = open_in filename in
  unwind_protect
     (fun () -> fn fp)
     (fun () -> close_in fp)

This allows the function fn to operate on the opened file and it guarantees
that the file gets closed regardless of how the function exits (normally, or
abnormally).

D.McClain