I'm trying to write small utilities to get used to Unix programming with OCaml. Here's my try for cat
:
open Unix ;;
let buffer_size = 10
let buffer = String.create buffer_size
let rec cat = function
| [] -> ()
| x :: xs ->
let descr = openfile x [O_RDONLY] 0 in
let rec loop () =
match read descr buffer 0 buffer_size with
| 0 -> ()
| _ -> print_string buffer; loop () in
loop ();
print_newline ();
close descr;
cat xs ;;
handle_unix_error cat (List.tl (Array.to_list Sys.argv))
It seems that the problem is that, on the last call to read
, the buffer doesn't entirely fill since there's nothing more to read, the end of what the buffer previously contained gets printed too. I read a few example codes using read
and they didn't seem to use String.create
every time they refill the buffer (which, anyway, still fills it with some characters...) ; so what should I do? Thanks.
The return of Unix.read
(which you ignore, except checking for 0) is the number of characters that you've read, so you only should use that many characters of the buffer.
But really, why bother using the low-level Unix stuff? Why not use the regular OCaml file opening and reading functions?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With