【问题标题】:How to read bytes from a file如何从文件中读取字节
【发布时间】:2020-02-03 01:46:28
【问题描述】:

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

:- 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>

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

【问题讨论】:

  • 我也不介意指向从文件中读取字节列表的更好方法的指针,因为我需要用纯序言而不是使用库谓词来编写它似乎令人惊讶.
  • 你需要说open(File, read, D, [type(binary)])。但是你真的想要字节吗? (这不是 SWI 特有的)
  • 谢谢,将此作为答案发布,我可以接受。我正在尝试为二进制格式编写解析器,所以我认为获取字节确实是我想要做的

标签: file stream prolog byte file-read


【解决方案1】:

要读取二进制文件,您需要指定选项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 进行了尝试,它按预期打印了文件的第一个字节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多