简体   繁体   中英

Writing cat in OCaml: use of Unix.read

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM