Two symbolic Delimiters can be specified:
end_of_line a newline or carriage-return/newline sequence
end_of_file the end of the file/input
End of file always acts like a delimiter.
If Length is a variable, it is unified with the length of the string String. If Length is an integer, the number of characters read from the input stream Stream is limited by Length.
Success:
?- read_string(input, "123", Length, String).
abcdef2ghi
Length = 6
String = "abcdef"
yes.
?- read_string(input, " \t", Length, String).
one two
Length = 3
String = "one"
yes.
?- read_string(input, end_of_line, Length, String).
abcdefghi
Length = 9
String = "abcdefghi"
yes.
?- read_string(input, end_of_line, 6, String).
abcdefghi
String = "abcdef"
yes.
?- open(file1, read, s).
yes.
?- system('cat file1').
abcd
yes.
?- read_string(s, "", Length, String).
Length = 5
String = "abcd\n" % Read up to end of file
yes.
% Code example: read lines from a file and return
% a list of strings, each string containing a line
get_lines(File, Lines) :-
open(File, read, S),
stream_get_lines(S, Lines),
close(S).
stream_get_lines(S, Lines) :-
( read_string(S, end_of_line, _, Line) ->
Lines = [Line|Ls],
stream_get_lines(S, Ls)
;
Lines = []
).
Fail:
?- open(string(""),read,s), read_string(s,"",L,String).
no (more) solution. % EOF - Error 190 - handler fails
Error:
read_string(Stream, "", Length, String). (Error 4).
read_string(stream, Dels, Length, String). (Error 4).
read_string("stream", "", Length, String). (Error 5).
read_string(stream, 12, Length, String). (Error 5).
read_string(stream, "", "abc", String). (Error 5).
read_string(stream, "", Length, 12). (Error 5).
read_string(stream, stop, Length, String). (Error 6).
read_string(output, "", Length, String). (Error 192).
read_string(atom, "", Length, String). (Error 193).