6

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?

Community
  • 1
  • 1
user3568104
  • 93
  • 1
  • 2
  • 7
  • possible duplicate of [How read a file and write another file in prolog](http://stackoverflow.com/questions/16855982/how-read-a-file-and-write-another-file-in-prolog) – lurker May 01 '14 at 16:33
  • If each of the line is a predicate, such as `subtype("apple","fruit")`, and the input file were written by Prolog I/O originally, my question is, how do you write to file with a period at the end in the first place? – vw511 Apr 05 '19 at 03:14

2 Answers2

7

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.

Paulo Moura
  • 18,373
  • 3
  • 23
  • 33
5

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.

lurker
  • 56,987
  • 9
  • 69
  • 103