本文介绍了OCaml:输入重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反正有将输入文件重定向到OCaml中的程序吗?

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

类似这样的东西:

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

我已经用谷歌搜索了这个问题.我想到了模块Unix,但我真的不明白它是如何工作的.

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

有人可以给我一些建议吗?如果我对Unix模块是正确的,请给我一个有关它如何工作的示例吗?!

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?!

非常感谢!

推荐答案

由于您知道如何从命令行进行重定向,因此我假设您正在询问如何在程序内部进行重定向.

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

要弄清楚的第一件事(如果您能原谅我的话)是您要这样做的原因.通过重定向可以完成的任何操作都可以通过打开文件进行输入并在输入通道中传递来完成.重定向的唯一目的是将 standard 输入通道连接到所选文件.但是,由于您正在编写代码,因此可以从任何您喜欢的渠道读取输入.

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.

如果您确实确实想要重定向stdin,并且您正在运行类似Unix的系统,则可以使用Shell实际处理重定向的方式:通过dup2()系统调用.

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 =

这篇关于OCaml:输入重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-21 02:23