Input/Output & Files
Standard streams: user_input, user_output, user_error.
20.1 Writing terms
write(hello), nl. % hello
print(f('A', "s")). % uses portray / writeq style
writeq('Hello World'). % 'Hello World' (quoted, re-readable)
write_canonical([a, 'B'|_]). % ignores operators, quotes
write_term(T, [quoted(true), max_depth(3)]).
writeln(x). % write + newline
portray_clause((a :- b, c)). % pretty-print a clause
print_message(error, format("bad ~w", [x])).20.2 format/2,3
integer (~D with commas) ~f / ~e / ~g floats (~2f) string / code list repeat (format("~*c", [5, 0'x]))
format("Hello, ~w!~n", [world]).
format("~a has ~d items costing ~2f~n", [ann, 3, 9.5]).
format("~q ~p ~s ~e ~t~20|~w~n", ['A b', x, "codes", 1.0, right]).
format(atom(A), "~w-~w", [x, y]). % to atom (also string(S), codes(C))20.3 Reading
?- read(X). % reads a term terminated by '.'
?- read_term(user_input, T, [variable_names(Vs)]).
?- read_line_to_string(user_input, S).
?- read_line_to_codes(user_input, Cs).
?- get_char(C), peek_char(C2), put_char(a).20.4 Files & streams
Standard streams: user_input, user_output, user_error. see/tell (Edinburgh-style) also exist but are legacy.
% Writing
write_file(File) :-
setup_call_cleanup(
open(File, write, Out),
format(Out, "line ~w~n", [1]),
close(Out)).
% Reading all terms
read_terms(File, Terms) :-
setup_call_cleanup(open(File, read, In), read_all(In, Terms), close(In)).
read_all(In, Terms) :-
read_term(In, T, []),
( T == end_of_file -> Terms = [] ; Terms = [T|Rest], read_all(In, Rest) ).
% Reading lines (SWI)
?- read_file_to_string('data.txt', S, []).
?- read_file_to_terms('facts.pl', Ts, []).
?- read_file_to_codes('data.txt', Cs, []).
?- open('log.txt', append, S), writeln(S, entry), close(S).
?- with_output_to(string(S), listing(member/2)).20.5 Files & OS
exists_file(F), exists_directory(D), directory_files('.', Fs), delete_file(F),
rename_file(A, B), make_directory(D), working_directory(Old, New),
absolute_file_name(F, Abs), file_base_name(P, B), file_name_extension(Base, Ext, F),
directory_file_path(Dir, File, Path), expand_file_name('*.pl', L),
shell('ls -l'), shell('ls', Status), getenv('HOME', H), setenv(x, 1),
process_create(path(git), [status], [stdout(pipe(Out))]). % library(process)20.6 Command-line programs
:- initialization(main, main).
main(Argv) :-
argv_options(Argv, Positional, Options), % library(main)
format("Args: ~w, Options: ~w~n", [Positional, Options]).swipl script.pl --verbose=true file.txt