PDA

View Full Version : Reading a file in O'Caml?


GnuVince
05-21-2002, 11:59 PM
In order to get an entry in Inkedmn's challenge, I am looking on how to read a file in O'Caml. So far I've found this:


# let gpl = open_in "gpl.txt";;
val gpl : in_channel = <abstr>
# input_line gpl;;
- : string = "\t\t GNU GENERAL PUBLIC LICENSE"
#


And after I have the last line, OCaml raises an exception: End_of_file. How would I use that in a loop (that's my big question). I tried the following:


# while not End_of_file do
Printf.printf "%s\n" (input_line gpl)
done;;
This expression has type exn but is here used with type bool
#


but as you can see, I get a type error. I am wondering if O'Caml is "qualified" to do this task, or if I would be better with another language?

PrBacterio
05-22-2002, 12:37 AM
Its an exception, and thus must be caught, not used in an expression; use the try / with construct:
try
while true do
print_string (input_line f_in ^ "\n")
done
with
| End_of_file -> ()