使用因子读取文件时如何等待更多内容?

How to Wait for more Content when Reading a File with Factor?

我有类似下面的代码

"file.txt" utf8 <file-reader> [ [ print ] each-line ] with-input-stream* ;

这适用于 file.txt 的当前内容,并且处理(如本例中的打印)在到达文件末尾时结束。但我希望进程等待附加到文件的新内容并处理它。或者换句话说,当前版本实现了 Unix cat,但我希望它实现 tail -f.

我希望 with-input-stream*(注意星号)可以解决问题,因为文档说流最后没有关闭。但一定还有其他我想念的东西。

你很幸运,我刚才写了一个类似的实用程序。参见 https://github.com/bjourne/playground-factor/wiki/Tips-and-Tricks-Filesystem#tailing-a-file

USING: accessors io io.encodings.utf8 io.files io.monitors kernel namespaces ;
IN: examples.files.tail

: emit-changes ( monitor -- )
    dup next-change drop
    input-stream get output-stream get stream-copy* flush
    emit-changes ;

: seek-input-end ( -- )
    0 seek-end input-stream get stream>> stream-seek ;

: tail-file ( fname -- )
    [
        dup f <monitor> swap utf8 [
            seek-input-end emit-changes
        ] with-file-reader
    ] with-monitors ;

我认为你的问题是给予 with-input-stream* 的报价将隐式关闭流(each-line 会这样做)。我不知道这是否是错误。像这样的一句话可以不用关闭就可以读全流:

: my-stream-contents* ( stream -- seq )
    [ [ stream-read1 dup ] curry [ ] ] [ stream-exemplar produce-as nip ] bi ;

然后:

IN: scratchpad "/tmp/foo" utf8 <file-reader> [ my-stream-contents* print ] keep
file contents here
...

--- Data stack:
T{ decoder f ~input-port~ utf8 f }
IN: scratchpad my-stream-contents* print
more file contents here
...