OCaml: input redirection

醉酒当歌 提交于 2019-12-13 04:42:06

问题


Is there anyway to redirect the input file into our program in OCaml?

Something like this:

filename.ml < input.<can be any extension>

I have googled for this problem. The module Unix comes up to mind but I really don't understand how it works.

Could someone please give me some suggestion? If I'm right about the Unix module, can you please give me an example of how it works?!

Thank you very much!


回答1:


Since you know how to redirect from the command line, I assume you're asking how to redirect inside your program.

The first thing to figure out (if you'll excuse my saying so) is why you would want to do this. Anything that can be done through redirection can be done by opening a file for input and passing around the input channel. The only purpose of redirection is to hook the standard input channel up to a chosen file. But since you're writing the code you can read input from any channel you like.

One reason to do it is that it's a quick hack for testing. I've done this many times. Another possible reason is that you're using code you can't easily or (don't want to) modify.

If you really do want to redirect stdin, and you're running on a Unix-like system, you can handle redirection the way the shell actually handles it: with the dup2() system call.

$ cat redir.ml
let redir fn =
    let open Unix in
    let fd = openfile fn [O_RDONLY] 0 in
    dup2 fd stdin

let () =
    redir "redir.ml";
    Printf.printf "%s\n" (read_line())
$ ocamlc -o redir unix.cma redir.ml
$ ./redir
let redir fn =


来源:https://stackoverflow.com/questions/22257343/ocaml-input-redirection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!