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
open
to open a file for writing. - Use
set_output
to direct output to the newly opened file. - Use
put_char
,nl
,write
andwrite_canonical
to write content to the file. - Use
close
to close the file.
The process for reading from a file is:
- Use
open
to open a file for reading. - Use
set_input
to specify the newly opened file as the source for input. - Use
get_char
andread
to read content from the file. - Use
close
to 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
yes
Read 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').
yes
Perform a query which uses the facts consulted from the newly written file.
?- a(1, X, 3, [a,b]).
X = 2
yes
Confirm streams and reset them.
?- current_input(X).
X = io_test.tmp_input_handle
yes
?- set_input('user_input').
yes
?- current_input('user_input').
yes
Note: "seeing" is a synonym for "current_input".
?- seeing('user_input').
yes
?- set_output('user_output').
yes
Example 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
yes
If 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