Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Re: files & handlers...
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Markus Mottl <mottl@m...>
Subject: Re: files & handlers...
> What would the language have to support in order that opened files be
> automatically closed when they get out of reach from the program? Is it
> what is called "finalization"?

Yes, this would be one solution. However, there are some drawbacks to using
finalization. In fact, even the "destructor-oriented" approach in C++
suffers from this deficiency: it is possible that the file/socket/whatever
is only closed at a much later point of time than expected.

For example, there might be a long running loop between the call to the
destructor (or lots of computation without GC-triggering allocation) before
the file is closed again.

If you want to make sure that closing happens immediately after the desired
operation, you will either have to state so explicitely (inconvenient) or
use a "higher-order" trick:

  let do_file name f =
    let file = open_in name in
    f file;
    close_in file

Then you can write something like:

  do_file "foo" (fun file -> ...)

and the file will be closed again.

If you happen to use the PCRE-library (Perl Compatibility Regular
Expression) for OCaml, there are two useful functions for such things,
namely "foreach_file" and "foreach_line".


  open Pcre

  let _ =
    foreach_file ["foo"; "bar"] (fun (name, file) ->
      print_endline ("Processing: " ^ name);
      foreach_line in: file (fun line ->
        print_endline ("line: " ^ line)

Using this, you cannot forget to close files again.

Best regards,
Markus Mottl

Markus Mottl,,