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
[Caml-list] (Sorry for my last post) lazyness, exceptions?, ocaml syntax rule-of-thumbs
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2002-09-27 (15:08)
From: Maxence Guesdon <maxence.guesdon@i...>
Subject: Re: [Caml-list] (Sorry for my last post) lazyness, exceptions?, ocaml syntax rule-of-thumbs

> Kontra, Gergely wrote:
>   > One point was ocaml is really obscure is the file reading: it needed to
>   > wrap the line-reading in an infinite loop, and this loop is ended via an
>   > exception. I think End_of_file is not an exception, it is just an event.

What next ? int_of_string "foo" returning None ?

It is an exception case: your function tries to read a line but there is nothing to read so it will not return the expected result, so an exception is raised. It is the classic and right way to do.

If you want to read a whole file as a string, you can use the following function:

let input_file_as_string file =
  let chanin = open_in_bin file in
  let len = 1024 in
  let s = String.create len in
  let buf = Buffer.create len in
  let rec iter () =
      let n = input chanin s 0 len in
      if n = 0 then
         Buffer.add_substring buf s 0 n;
         iter ()
      End_of_file -> ()
  iter ();
  close_in chanin;
  Buffer.contents buf

Maxence Guesdon
To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: