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
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2005-01-25 (22:54)
From: Oliver Bandel <oliver@f...>
Subject: Re: [Caml-list] open_file
On Tue, Jan 25, 2005 at 10:19:30PM +0000, yjc01@doc.ic.ac.uk wrote:
> I tried to read in a text file and extract the string between (* and *) into a 
> variable, buff, by using the openfile and read functions in Unix module. But 
> get an error on compilation.
> The code I came up with is as follows: 
> open Unix;;
> let file_reader = openfile "sudent.cd" [O_RDONLY] 0o640;;

assuming the file "sudent.cd" exists and contains enough bytes.

> let buff = ref "empty";;
> let main () =
>   let file_content = read file_reader !buff 1 5 in
>   print_int file_content;
>   print_string !buff;;
> main ();

assuming you meant

main ();;

in the last line,....

then you have a problem, when you read from position with index "1" (instead of "0"
for the fiorst byte) and read 5 bytes into the 5 byte long string....

There is not enough space in your buffer for writing all your data into it.

You may start writing at position 0 instead of 1 or only read in 4 bytes, or
make your buffer larger.

You may set the len of bytes to the size of bytes of your String
(String.length !buff) . But you have to write from position (offset) 0.

It would be better to use the  try/with
construct around your unix-calls; then you can handle exceptions.

E.g. when there is no file "sudent.cd" then your program fails
in your first line.