Before I/O operations can take place on a stream, the stream must be opened, and it must be set to be current input or current output. As illustrated in the figure “Categorization of Stream Handling Predicates”, the operations of opening and setting are separate with respect to the stream predicates, and combined in the File Specification Predicates.
open(
File,
Mode,
Stream)
attempts to open the file
File in the mode specified (read,write or append). If the
open/3
request is successful, a stream object, which can be
subsequently used for input or output to the given file, is unified
with Stream.
The read
mode is used for input. The write
and
append
modes are used for output. The write
option causes
a new file to be created for output. If the file already exists,
it is set to empty and its previous contents are lost. The
append
option opens an already-existing file and adds output to
the end of it. The append
option will create the file if it does
not already exist.
Options can be specified by calling open/4
.
set_input(
Stream)
makes Stream the current input stream.
Subsequent input predicates
such as read/1
and get_code/1
will henceforth use this stream.
set_output(
Stream)
makes Stream the current output stream.
Subsequent output
predicates such as write/1
and put/1
will henceforth use this
stream.
Opening a stream and making it current are combined in see
and tell
:
see(
S)
makes file S the current input stream.
If S is an atom, it is taken to be a file specification, and
see/1
, it is made the current input stream;
see/1
fails. In addition, if the
fileerrors
flag is set (as it is by default), see/1
sends
an error message to the standard
error stream and calls abort/0
, returning to the top level.
tell(
S)
makes S the current output stream.
tell/1
, it is made the current output
stream;
tell/1
fails. In addition, if the
fileerrors
flag is set (which it is by default), tell/1
sends
an error message to the standard
error stream and calls abort/0
, returning to the top level.
It is important to remember to close streams when you have finished with
them. Use seen/0
or close/1
for input files, and
told/0
or close/1
for output files.
open_null_stream(
Stream)
opens a text output stream that is not
connected to any file and unifies its stream object with Stream.
Characters or terms that are sent to this stream are thrown away.
This predicate is useful because various pieces of local state are
kept for null streams: the predicates
character_count/2
,
line_count/2
and line_position/2
can be used on these
streams (see ref-iou-sos).