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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With