Search code examples
ocamlocaml-core

Why does Core.Std deprecate the `close_in` and `close_out` functions?


If I open Core.Std, trying to use close_out function to close an out_channelgives me an error because Core changes the type signature of close_out to give me a deprecation error message.

close_out;;
- : [ `Deprecated_use_out_channel ] -> [ `Deprecated_use_out_channel ] = <fun>

First question: Why does Core deprecate close_out deprecated but not close_out_noerr?

Second question: Does Core still expect me to work with in_channels and out_channels or does it prefer that I use a different API for IO?

Third question: The only other IO API I could find are functions like read or write in the Unix module, which work on file descriptors instead of file handles. In C, the file descriptor functions emit syscalls directly while the ones from stdio.h that receive FILE * do buffered IO. Is this similar in Ocaml with the functions in Unix module emitting syscalls directly and the functions working with in_channel and out_channel do buffered IO?


Solution

  • If you look at the Real World Ocaml book, the author seems to make extensive use of the In_channel and Out_channel modules. Files are no more opened/closed using the Ocaml pervasive functions but with the In_channel.close and Out_channel.close functions.

    The problem is that if an exception is raised when reading the file, the programmer has to close the opened file when the exception is caught. There is no equivalent of garbage collector for opened files. Using In_channel.with_file takes care of proper file closing, even if an exception is raised.