Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing cat in OCaml: use of Unix.read

Tags:

unix

cat

ocaml

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.

like image 642
rochem Avatar asked Oct 11 '22 17:10

rochem


1 Answers

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?

like image 101
newacct Avatar answered Oct 13 '22 06:10

newacct