如何从文件中读取字节

How to read bytes from a file

我正在尝试使用 swipl 版本 8.0.3 将文件读入序言中的字节列表。

:- use_module(library(readutil)).

try_read_byte(File):-
    open(File, read, Stream),
    get_byte(Stream, B),
    print(B).

try_read_char(File):-
    open(File, read, Stream),
    get_char(Stream, C),
    print(C).

try_read_char 成功,但是当我调用 try_read_byte 时,出现错误:

ERROR: No permission to read bytes from TEXT stream `<stream>(0x56413a06a2b0)'
ERROR: In:
ERROR:    [9] get_byte(<stream>(0x56413a06a2b0),_9686)
ERROR:    [8] try_read_byte("test.pl") at /home/justin/code/decompile/test.pl:5
ERROR:    [7] <user>

从查看源代码 code/documentation (https://www.swi-prolog.org/pldoc/man?section=error) 来看,这似乎是一个类型错误,但我无法根据它弄清楚该怎么做。

要读取二进制文件,您需要指定选项type(binary)。否则 get_byte 按照标准(第 8.13.1.3 节)的规定提出 permission_error。这可能会造成混淆,因为用户可能正在检查正确的权限,这与问题的实际来源无关。

try_read_byte(File):-
    open(File, read, Stream, [type(binary)])),
    get_byte(Stream, B),
    write(B).

我刚刚用 Scryer Prolog 尝试了这个,它按预期打印了文件的第一个字节。