ocaml - 在标准输入上使用真的输入字符串进行非法搜索
问题描述
我正在改造一些代码以接受来自标准输入的输入(除了文件)。
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")
我如何让后者也工作?
解决方案
你没有提到你正在使用什么系统。
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 ()
推荐阅读
- sparql - SPARQL 构造。如何将 RDF 属性的值分配给实际的 RDF 变量
- mongodb - 使用 npm 脚本将测试用户导入 Meteor 应用程序?
- python - Matplotlib:TypeError:图像数据的尺寸无效
- javascript - Chrome 扩展 google oauth 2 问题
- r - 在 r 中相交比较向量
- sql - SQL Server - 插入和更新规范(外键关系)
- vba - excel vba将文件上传到sharepoint
- python - 为什么是“\xfc\xa9\xf1\xd2Mb\x80?” == 'ü©ñÒMb\x80?' 在 Python 中是真的吗?
- php - Volley 无法与服务器连接
- c - 用A、B、C三点坐标定义一个框