Possible Duplicate:
Read a file line by line in Prolog
I found the following prolog code which reads one character at a time and prints out.
process(File) :-
open('C:/Users/BHARAT/Desktop/a.txt', read, In),
get_char(In, Char1),
process_stream(Char1, In),
close(In).
process_stream(end_of_file, _) :- !.
process_stream(Char, In) :-
print(Char),
get_char(In, Char2),
process_stream(Char2, In).
But if the file has multiple lines is there a way to read 1 whole line at a time so that it will be easy for tokenizing.
You say you want to tokenize the input - the best way to do this are definite clause grammars (DCGs). With library(pio)
in SWI you can use the grammar directly to read in a file like so:
?- use_module(library(pio)).
?- phrase_from_file(seq(Xs),f).
seq([]) --> [].
seq([E|Es]) --> [E], seq(Es).
Replace now seq//1
by some more elaborate tokenizer.
SWI-Prolog has some support predicate, for instance:
..., read_line_to_codes(Stream, Codes), phrase(parse, Codes, []), ...
But I would advise you to adopt phrase_from_file/2 (as already suggested in another answer). There is a support library to help parsing input, with some ready to use parser:
:- use_module(library(http/dcg_basics)).
edit the support library has been renamed, there is a back compatibility trick, that allows old naming, but now it's better to use library(dcg/basics).
来源:https://stackoverflow.com/questions/8231754/reading-a-file-in-prolog