Prolog provides commands to enable the input and output of characters and terms to the filesystem.
The current_output and current_input commands can be used to identify the current source of output and input.
The process for writing to a file is:
- Use
opento open a file for writing. - Use
set_outputto direct output to the newly opened file. - Use
put_char,nl,writeandwrite_canonicalto write content to the file. - Use
closeto close the file.
The process for reading from a file is:
- Use
opento open a file for reading. - Use
set_inputto specify the newly opened file as the source for input. - Use
get_charandreadto read content from the file. - Use
closeto close the file.
Examples
Write Prolog syntax to a file.
?- open('io_test.tmp', write, Z), put_char(b), set_output(Z), write(a(1,2,3,[a,b])), put_char('.'), close(Z).
bZ = io_test.tmp_output_handle
yesRead the contents of the newly written file.
?- open('io_test.tmp', read, Z), set_input(Z), read(Y), close(Z).
Y = a(1, 2, 3, [a,b])
Z = io_test.tmp_input_handle
yes"Consult" the facts defined in the newly written file.
?- consult('io_test.tmp').
yesPerform a query which uses the facts consulted from the newly written file.
?- a(1, X, 3, [a,b]).
X = 2
yesConfirm streams and reset them.
?- current_input(X).
X = io_test.tmp_input_handle
yes
?- set_input('user_input').
yes
?- current_input('user_input').
yesNote: "seeing" is a synonym for "current_input".
?- seeing('user_input').
yes
?- set_output('user_output').
yesExample of an error when the file to be read does not actually exist.
?- open('directory_that_doesnt_exist/some_file.xyz','read',Z).
Unable to open input for: directory_that_doesnt_exist/some_file.xyz"see/1" is a convenient way, with a single statement, to both open an input stream and set it as the current input stream.
?- see('io_test.tmp').
yes
?- get_char(X).
X = a
yes
?- current_input(X).
X = io_test.tmp_input_handle
yes"seen" is a convenient way, with a single statement, to both close the current input stream and set user_input as the current input stream.
?- seen.
yes
?- current_input(X).
X = user_input
yesIf the argument of "see/1" is a file handle, rather than a filename, then the current input stream is set to the stream represented by the handle.
?- open('io_test.tmp', read, W), see(W), current_input(X), get_char(Y), seen, current_input(Z).
W = io_test.tmp_input_handle
X = io_test.tmp_input_handle
Y = a
Z = user_input
yes"tell/1" is a convenient way, with a single statement, to both open an output stream and set it as the current output stream. "told" is a convenient way, with a single statement, to both close the current output stream and set user_output as the current output stream.
?- tell('io_test.tmp'), put_char(x), told, see('io_test.tmp'), get_char(Y), seen.
Y = x
yes