3

I am trying to import library(readutil) module in order to read a line from my file. However when I try the following:

:- use_module(library(readutil)).

read_from_file(File) :-
    open(File,read,Stream),
    read_line_to_codes(Stream,Codes),
    write(Codes),
    close(Stream).

I get the error:

error(existence_error(procedure,read_line_to_codes/2),read_from_file/0)

How can I properly import that module? The module description is here: http://www.swi-prolog.org/pldoc/man?section=readutil

Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
Mandy
  • 145
  • 6

2 Answers2

2

A portable alternative, that you can use with GNU Prolog and a dozen more Prolog systems, is to install Logtalk (version 3.36.0 or later) and use its reader library, which provides a similar API to SWI-Prolog library(readutil). You can consult the reader library API at:

https://logtalk.org/library/reader_0.html

Usage is simple. Start Logtalk with GNU Prolog as the backend compiler by using the gplgt or gplgt.sh script (if on a POSIX system) or the start menu shortcut (if on Windows). Load the library using the query:

| ?- {reader(loader)}.

or by using the goal logtalk_load(library(reader_loader) if not at the top-level interpreter. Upon loading, you can play with the API. For example:

| ?- reader::file_to_codes('$LOGTALKUSER/VERSION.txt', Codes).

Codes = [51,46,50,53,46,48,45,98,50,49,10]

yes

| ?- reader::file_to_chars('$LOGTALKUSER/VERSION.txt', Codes).

Codes = ['3','.','3','7','.','0',-,b,'0','1','\n']

yes
Paulo Moura
  • 18,373
  • 3
  • 23
  • 33
1

I found the answer to my own question which requires copying the SWI prolog source code for this particular predicate into your own code:

/*This is a copied predicate from SWI prolog */
read_line_to_codes(Stream, Codes) :-
    get_code(Stream, C0),
    (   C0 == -1
    ->  Codes0 = end_of_file
    ;   read_1line_to_codes(C0, Stream, Codes0)
    ),
    Codes = Codes0.

read_1line_to_codes(-1, _, []) :- !.
read_1line_to_codes(10, _, []) :- !.
read_1line_to_codes(13, Stream, L) :-
    !,
    get_code(Stream, C2),
    read_1line_to_codes(C2, Stream, L).

read_1line_to_codes(C, Stream, [C|T]) :-
    get_code(Stream, C2),
    read_1line_to_codes(C2, Stream, T).
Mandy
  • 145
  • 6