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] Better option to read a file
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2004-03-17 (10:12)
From: Markus Mottl <markus@o...>
Subject: Re: [Caml-list] Better option to read a file

I usually use one of the two functions below to read in whole strings.
Function "read_file" does the obvious: read a file as fast as possible
into a string.

Function "read_channel" reads a channel of unbounded size (as long as the
maximum string length is not exceeded, of course).  It also takes the
optional argument "buf_size", which you can set depending on the kind
of channel you read from (the default 4096 bytes are somewhat optimal
when reading from files on Linux).

let rec copy_lst res ofs = function
  | [] -> res
  | (str, len) :: t ->
      let pos = ofs - len in
      String.unsafe_blit str 0 res pos len;
      copy_lst res pos t

let read_channel ?(buf_size = 4096) =
  let rec loop len lst ch =
    let buf = String.create buf_size in
    let n = input ch buf 0 buf_size in
    if n <> 0 then loop (len + n) ((buf, n) :: lst) ch
    else copy_lst (String.create len) len lst in
  loop 0 []

let read_file name =
  let file = open_in name in
  let size = in_channel_length file in
    let buf = String.create size in
    really_input file buf 0 size;
    close_in file;
  with exc ->
    (try close_in file with _ -> ());
    raise exc

Markus Mottl

Markus Mottl

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