English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
RE: [Caml-list] closing file descriptors and channels
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2003-11-20 (16:55)
From: Christian Schaller <Christian.Schaller@s...>
Subject: RE: [Caml-list] closing file descriptors and channels
> close_out and close_in both perform the equivalent of a Unix.close on
> the underlying Unix file descriptor, and, yes, closing something that
> is already closed is an I/O exception.  So, one possibility is to
> close only one of the three entities file_descr, oc and ic.  It's best
> to close the output channel oc, since this will flush its buffer.

What I did was just skipping the Unix.close, but close *both* in- and
out-channels and it worked (until now ;-) ).

> Side remark: you'd need to close the file descriptor also in the case
> where the line is found and the exception Found is raised.

Yup, I've seen this one already.  This one makes it complicated, since
for propagating the exception, I have to duplicate the closings:

  End_of_file -> output_string oc (line ^ "\n");
  Found line -> (close_out oc; close_in ic; raise Found line);
  close_out oc;
  close_in ic

Since I am new to streams & co, are there any kind of rules when to
prefer streams to normal I/O?  Is there more overhead when using
streams?  Shouldn't I use streams when working on a regular text file?

What if I want to break from a stream with an exception (as above the
Found exception)?  Closing/accessing the channel is only possible in the
stream creation as in my corrected version:

let read_lines ch =
  let read_new_line n =
    try Some (input_line ch)
    with End_of_file -> close_in ch; None in
  Stream.from read_new_line

Now I want to stop reading lines after a certain number of lines

let rec read_n_lines n =
  [< 'line; rest >] -> if n <> 0 then print_endline line; read_n_lines
(n-1) else ()
  [< >] -> ()

Didn't type-check it, though ;-)  Anyway, how can I close the stream in
this case?


- Chris

To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners