Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog - unexpected end of file

Tags:

io

input

prolog

Reading a file in Prolog error

Hi, I'm working on a Prolog project and I need to read the whole file in it. I have a file named 'meno.txt' and I need to read it. I found some code here on stack. The code is following:

main :-
  open('meno.txt', read, Str),
  read_file(Str,Lines),
  close(Str),
  write(Lines), nl.


read_file(Stream,[]) :-
    at_end_of_stream(Stream).


read_file(Stream,[X|L]) :-
    \+ at_end_of_stream(Stream),
    read(Stream,X),
    read_file(Stream,L).

When I call the main/0 predicate, I get an error saying unexpected end of file. My file looks like this:

line1
line2
line3
line4

I also found the similar problem here and the solution where in ASCII and UTF coding but I tried that and it seems its not my solution. Can anyone help?

like image 277
user3568104 Avatar asked Dec 19 '22 15:12

user3568104


2 Answers

The predicate read/2 reads Prolog terms from a file. Those must end with a period. Try updating the contents of your file to:

line1.
line2.
line3.
line4.

The unexpected end of file you're getting likely results from the Prolog parser trying to find an ending period.

like image 131
Paulo Moura Avatar answered Dec 25 '22 22:12

Paulo Moura


If you are using SWI Prolog, you may use something like this for the read:

read_file(Stream,[X|L]) :-
    \+ at_end_of_stream(Stream),
    read_line_to_codes(Stream,Codes),
    atom_chars(X, Codes),
    read_file(Stream,L), !.

read_line_to_codes/2 reads each line directly into an array of character codes. Then atom_chars/2 will convert the codes to an atom.

like image 33
lurker Avatar answered Dec 26 '22 00:12

lurker