Version française
Home     About     Download     Resources     Contact us    
Browse thread
Reading a whole file into memory
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Stalkern 2 <stalkern2@t...>
Subject: Re: "ocaml_beginners"::[] Reading a whole file into memory
Il Wednesday 07 May 2003 21:58, Brian Hurt ha scritto:
> let read_whole_file chan =
> let buf = Buffer.create 4096 in
> let rec loop () =
> let newline = input_line chan in
> Buffer.add_string buf newline;
> Buffer.add_char '\n';
> loop ()
> in
> try
> loop ()
> with
> End_of_file -> Buffer.contents buf

Just to remember that reading line by line is not necessary: One can use 
String and input instead of Buffer and input_line


let read_whole_file chan =
let fileRead = ref "" in 
(*we'll store results here before the EOF exception is thrown*)
let bufSize = 4096 in
let buf = String.create bufSize in (*rewritable buffer*)
let rec reader accumString =
let chunkLen = input chan buf 0 bufSize in (*input up to bufSize chars to 
buf*)
if (chunkLen > 0) then (*more than 0 chars read*)
let lastChunk = String.sub buf 0 chunkLen (*getting n chars read*) in
reader (accumString^lastChunk) 
else 
accumString (*this case will occur before EOF*)
in
try
let () = (fileRead := (reader "")) in (*reader stops and returns at 0 
chars read*)
!fileRead (*this will never be reached, EOF comes before*)
with
End_of_file -> !fileRead;; (*so we go and retrieve the string read*)


Notice that the buffer here has fixed size, unlike the ones provided by the 
Buffer module that implements extensible string buffers.

Ciao
Ernesto