如何在 SWI-Prolog 中处理 `user_input` 或 `user_output` 上的二进制数据?

How to process binary data on `user_input` or `user_output` in SWI-Prolog?

我想用 Prolog 编写一个处理二进制数据的程序。它应该以 UNIX 方式运行,即如果没有给出参数,它应该从 stdin / user_input and write to stdout / user_output 中读取以充当 中的 filter管道.

只要我的数据是文本的,一切都 运行 没问题,但是一旦我的数据是二进制的,输出就会很奇怪,完全不是我预期的,有时我会收到奇怪的消息,比如 Illegal multibyte Sequence。我使用 open/3.

打开的流也会发生同样的情况

默认情况下,user_inputuser_output 设置为 type(text)encoding(X),其中 X 是源自环境的平台编码。如果要处理二进制数据,则需要将流的类型更改为type(binary)或将流的编码更改为encoding(octet)。您可以使用 set_stream/2,像这样:

:- set_stream(user_input, type(binary)).
:- set_stream(user_output, type(binary)).

:- set_stream(user_input, encoding(octet)).
:- set_stream(user_output, encoding(octet)).

对于您自己打开的流,您也可以使用 open/4 代替,即 open(Filename, read, StreamIn,[type(binary)])open(Filename, read, StreamIn,[encoding(octet)]).

当您读取的是真正的二进制数据时,type(binary) 是首选方法。