File I/O and Finalization

From: David McClain (dmcclain@azstarnet.com)
Date: Mon Feb 07 2000 - 16:08:58 MET

  • Next message: Stefan Monnier: "Re: files & handlers..."

    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



    This archive was generated by hypermail 2b29 : Mon Feb 07 2000 - 19:46:45 MET