The command read/1
serves to read terms > of a file with the same Prolog syntax. To read arbitrary content (ie strings) you will need the methods of reading primitive characters , like for example get_char/1
. An example (without going into the merit of file encoding, which I assume you've already specified when opening the input stream) would be:
ler_chars(S) :-
get_char(C),
ler_resto(C,S).
ler_resto(end_of_file, []).
ler_resto(C, [C|R]) :-
get_char(C2),
ler_resto(C2, R).
After calling ler_chars
in a stream , its contents will be returned in a list of characters. If you want this content in a string, just call atom_chars/2
in the result: / p>
?- abrir_stream, ler_chars(Chars), atom_chars(String, Chars).
But a better option is to interpret the contents of this file through a DCG grammar. From what I understand, you have a series of names separated by spaces or line breaks, right? And each name consists of nome.sobrenome
. This expressed in DCG would look like:
nomes([]) --> [].
nomes([Nome|R]) --> nome(Nome), [' '], nomes(R).
nomes([Nome|R]) --> nome(Nome), ['\n'], nomes(R).
nomes([Nome]) --> nome(Nome).
nome(pessoa(Nome,Sobrenome)) --> palavra(CNome), ['.'], palavra(CSobrenome),
{ atom_chars(Nome, CNome),
atom_chars(Sobrenome, CSobrenome) }.
palavra([]) --> [].
palavra([C|R]) --> [C], { is_alpha(C) }, palavra(R).
Calling this code in the reading result gives you a list where each element is of the form pessoa(Nome,Sobrenome)
:
?- abrir_stream, ler_chars(Chars), nomes(Pessoas, Chars, []).
Pessoas = [pessoa(iago, neves), pessoa(pedro, santos), pessoa(joao, vitor), pessoa(larissa, figueiredo)]
Example on ideone.