Writing a Cat in OCaml: Using Unix.read

I am trying to write small utilities to get used to Unix programming with OCaml. Here is my attempt 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 the last call readdoes not fill the buffer completely, since there is nothing more readable, the end is that the buffer was previously printed. I read a few code examples using read, and they didn't seem to use String.createevery time they replenish the buffer (which, in any case, still fills it with some characters ...); So what should I do? Thank.

+5
source share
1 answer

Unix.read ( , 0) - , , .

, Unix ? OCaml?

+4

All Articles