简体   繁体   English

在OCaml中编写cat:使用Unix.read

[英]Writing cat in OCaml: use of Unix.read

I'm trying to write small utilities to get used to Unix programming with OCaml. 我正在尝试编写小实用程序以习惯使用OCaml进行Unix编程。 Here's my try for cat : 这是我对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. 看来,问题是,在最后调用read ,缓冲区不完全填补,因为没有什么更多的阅读,以前包含在buffer被打印的内容也结束。 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...) ; 我使用read读取了一些示例代码,并且每次重新填充缓冲区时它们似乎都没有使用String.create (无论如何,仍然用一些字符填充它...); 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. Unix.read的返回(你忽略,除了检查0)是你读过的字符数,所以你只应该使用缓冲区的那么多字符。

But really, why bother using the low-level Unix stuff? 但实际上,为什么要使用低级Unix的东西呢? Why not use the regular OCaml file opening and reading functions? 为什么不使用常规的OCaml文件打开和读取功能?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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