Re: files & handlers...

From: Markus Mottl (mottl@miss.wu-wien.ac.at)
Date: Mon Feb 07 2000 - 16:46:55 MET

  • Next message: jean-marc alliot: "Typing problem"

    > 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".

    E.g.:

      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, mottl@miss.wu-wien.ac.at, http://miss.wu-wien.ac.at/~mottl
    



    This archive was generated by hypermail 2b29 : Tue Feb 08 2000 - 09:53:59 MET