首页 > 解决方案 > 在标准输入上使用真的输入字符串进行非法搜索

问题描述

我正在改造一些代码以接受来自标准输入的输入(除了文件)。

print_string (really_input_string stdin (in_channel_length stdin))

这在我重定向标准输入时有效:-

$ ./a.out < /tmp/lorem.txt 
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod 

但否则会在不等待我输入的情况下失败:-

$ ./a.out
Fatal error: exception Sys_error("Illegal seek")
$

或者:-

$ cat /tmp/lorem.txt | ./a.out 
Fatal error: exception Sys_error("Illegal seek")

我如何让后者也工作?

标签: ocaml

解决方案


你没有提到你正在使用什么系统。

Unix 查找操作仅对常规文件有意义,即存储在磁盘(或类似的随机可寻址媒体)上的文件。在通常的 Unix 实现中,终端设备或管道上的搜索被忽略。但是,在您使用的系统中,这些似乎被视为错误。这让我怀疑您没有使用类似 Unix(或足够类似 Unix)的系统。

无论如何,问题似乎在于in_channel_length寻找文件的末尾以确定它有多大。在您的系统中,当输入来自终端或管道时,这不起作用。

当输入来自管道或终端时,即使在 Unix 系统上,也很难看出代码如何按预期工作。

我建议您编写自己的循环来阅读,直到看到 EOF。

这是一个粗略的实现,对于文本文件来说可能已经足够了:

let my_really_read_string in_chan =
    let res = Buffer.create 1024 in
    let rec loop () =
        match input_line in_chan with
        | line ->
            Buffer.add_string res line;
            Buffer.add_string res "\n";
            loop ()
        | exception End_of_file -> Buffer.contents res
    in
    loop ()

推荐阅读