gpt4 book ai didi

ocaml - 重定向标准输出 OCaml

转载 作者:行者123 更新时间:2023-12-02 06:02:01 25 4
gpt4 key购买 nike

如何在 OCaml 中重定向标准输出?
我试过Format.set_formatter_out_channel但它似乎不起作用。当我之后使用 printf 时,文本仍然打印在屏幕上,而我创建的文件仍然是空的。

最佳答案

您的实验失败的原因是 Printf.printf 没有使用 Format 模块的输出 channel 。格式模块用于 pretty-print ,这是一项相当复杂的任务。 Printf.printf 函数将格式化数据写入标准输出(C 风格的 printf)。

您真的想重定向标准输出,还是只想写入特定 channel ?写入 channel oc你可以使用

Printf.fprintf oc ...

而不是
Printf.printf ...

做重定向是另一回事。您可以使用 Unix.dup2 .这是一个示例 session ,展示了如何做到这一点:
$ cat redirected
cat: redirected: No such file or directory

$ cat redir.ml
let main () =
let newstdout = open_out "redirected" in
Unix.dup2 (Unix.descr_of_out_channel newstdout) Unix.stdout;
Printf.printf "line of text\n";
Printf.printf "second line of text\n"

let () = main ()

$ ocamlopt -o redir unix.cmxa redir.ml
$ ./redir

$ cat redirected
line of text
second line of text

由于这是更改 OCaml I/O 系统背后的低级文件描述符,所以我会小心一点。作为一个快速破解它太棒了——我已经做过很多次了。

更新

这是上述代码的一个版本,它临时重定向标准输出,然后将其放回原来的位置。
$ cat redirected
cat: redirected: No such file or directory
$
$ cat redir.ml
let main () =
let oldstdout = Unix.dup Unix.stdout in
let newstdout = open_out "redirected" in
Unix.dup2 (Unix.descr_of_out_channel newstdout) Unix.stdout;
Printf.printf "line of text\n";
Printf.printf "second line of text\n";
flush stdout;
Unix.dup2 oldstdout Unix.stdout;
Printf.printf "third line of text\n";
Printf.printf "fourth line of text\n"

let () = main ()
$
$ ocamlopt -o redir unix.cmxa redir.ml
$ ./redir
third line of text
fourth line of text
$
$ cat redirected
line of text
second line of text

关于ocaml - 重定向标准输出 OCaml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19527859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com