From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: weis Received: (from weis@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id JAA22361 for caml-redistribution@pauillac.inria.fr; Tue, 8 Feb 2000 09:46:10 +0100 (MET) Resent-Message-Id: <200002080846.JAA22361@pauillac.inria.fr> Received: from nez-perce.inria.fr (nez-perce.inria.fr [192.93.2.78]) by pauillac.inria.fr (8.7.6/8.7.3) with ESMTP id QAA03631 for ; Mon, 7 Feb 2000 16:47:10 +0100 (MET) Received: from miss.wu-wien.ac.at (miss.wu-wien.ac.at [137.208.107.17]) by nez-perce.inria.fr (8.8.7/8.8.7) with ESMTP id QAA19278 for ; Mon, 7 Feb 2000 16:47:07 +0100 (MET) Received: (from mottl@localhost) by miss.wu-wien.ac.at (8.9.0/8.9.0) id QAA14260; Mon, 7 Feb 2000 16:46:55 +0100 (MET) From: Markus Mottl Message-Id: <200002071546.QAA14260@miss.wu-wien.ac.at> Subject: Re: files & handlers... To: debourse@email.enst.fr (Benoit de Boursetty) Date: Mon, 7 Feb 2000 16:46:55 +0100 (MET) Cc: caml-list@inria.fr (OCAML) In-Reply-To: from "Benoit de Boursetty" at Feb 05, 2000 11:37:19 AM X-Mailer: ELM [version 2.5 PL2] MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Resent-From: weis@pauillac.inria.fr Resent-Date: Tue, 8 Feb 2000 09:46:10 +0100 Resent-To: caml-redistribution@pauillac.inria.fr > 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