8.1.5 Stream I/O

The following predicates are relevant to stream I/O. Character, byte and line counts are maintained per stream. All streams connected to the terminal, however, share the same set of counts. For example, writing to user_output will advance the counts for user_input, if both are connected to the terminal. Bidirectional streams use the same counters for input and output.

Wherever a stream argument appears as input (+Stream), a stream alias can be used instead.

absolute_file_name(+FileSpec,-AbsFileName)
absolute_file_name(+FileSpec,-AbsFileName,+Options)

If FileSpec is user, then AbsFileName is unified with user; this “file name” stands for the standard input or output stream, depending on context. Otherwise, unifies AbsFileName with the first absolute file name that corresponds to the relative file specification FileSpec and that satisfies the access modes given by Options. Options is a list of zero or more of the following, the default being the empty list:

ignore_underscores(+Boolean)
Boolean must be true or false. If true, when constructing an absolute file name that matches the given access modes, two names are tried: First the absolute file name derived directly from FileSpec, and then the file name obtained by first deleting all underscores from FileSpec. If false (default), suppresses any deletion of underscores.
extensions(+Ext)
Has no effect if FileSpec contains a file extension. Ext is an atom or a list of atoms, each atom representing an extension (e.g. '.pl') that should be tried when constructing the absolute file name. The extensions are tried in the order they appear in the list. Default value is Ext = [”], i.e. only the given FileSpec is tried, no extension is added. To specify extensions('') or extensions([]) is equal to not giving any extensions option at all.
file_type(+Type)
Picks an adequate extension for the operating system currently running, which means that programs using this option instead of extensions(Ext) will be more portable between operating systems. This extension mechanism has no effect if FileSpec contains a file extension. Type must be one of the following atoms:
text
implies extensions([”]). FileSpec is a file without any extension. (Default)
source
implies extensions(['.pl',”]). FileSpec is a Prolog source file, maybe with a `.pl' extension.
object
implies extensions(['.po']). FileSpec is a Prolog object file.
ql
implies extensions(['.ql']). FileSpec is a QL file. Obsolescent.
saved_state
implies extensions(['.sav',”]). FileSpec is a saved-state, maybe with a `.sav' extension.
foreign_file
FileSpec is a foreign language object file, maybe with a system dependent extension.
foreign_resource
FileSpec is a foreign language shared object file, maybe with a system dependent extension.
directory
implies extensions([”]). FileSpec is a directory, not a regular file. Only when this option is present can absolute_file_name/3 access directories without raising an exception.

access(+Mode)
Mode must be an atom or a list of atoms. If a list is given, AbsFileName must obey every specified option in the list. This makes it possible to combine a read and write, or write and exist check, into one call. Each atom must be one of the following:
read
AbsFileName must be readable.
write
append
If AbsFileName exists, it must be writable. If it doesn't exist, it must be possible to create.
exist
The file represented by AbsFileName must exist.
none
The file system is not accessed. The first absolute file name that is derived from FileSpec is returned. Note that if this option is specified, no existence exceptions can be raised. (Default)

file_errors(+Val)
fileerrors(+Val)
Val is one of the following, where the default is determined by the current value of the fileerrors Prolog flag:
error
Raise an exception if a file derived from FileSpec has the wrong permissions, that is, can't be accessed at all, or doesn't satisfy the the access modes specified with the access option.
fail
Fail if a file derived from FileSpec has the wrong permissions. Normally an exception is raised, which might not always be a desirable behavior, since files that do obey the access options might be found later on in the search. When this option is given, the search space is guaranteed to be exhausted.

solutions(+Val)
Val is one of the following:
first
As soon as a file derived from FileSpec is found, commit to that file. Makes absolute_file_name/3 determinate. (Default)
all
Return each file derived from FileSpec that is found. The files are returned through backtracking. This option is probably most useful in combination with the option file_errors(fail).

relative_to(+FileOrDirectory)
FileOrDirectory should be an atom, and controls how to resolve relative filenames. If it is '', file names will be treated as relative to the current working directory. If a regular, existing file is given, file names will be treated as relative to the directory containing FileOrDirectory. Otherwise, file names will be treated as relative to FileOrDirectory.

If absolute_file_name/3 is called from a goal in a file being loaded, the default is the directory containing that file. Otherwise, the default is the current working directory.

The functionality of absolute_file_name/3 is most easily described as a four phase process, in which each phase gets an infile from the preceding phase, and constructs one or more outfiles to be consumed by the succeeding phases. The phases are:

  1. Syntactic rewriting
  2. Underscore deletion
  3. Extension expansion
  4. Access checking

Each of the three first phases modifies the infile and produces variants that will be fed into the succeeding phases. The functionality of all phases but the first are decided with the option list. The last phase checks if the generated file exists, and if not asks for a new variant from the preceding phases. If the file exists, but doesn't obey the access mode option, a permission exception is raised. If the file obeys the access mode option, absolute_file_name/3 commits to that solution, subject to the solutions option, and unifies AbsFileName with the file name. For a thorough description, see below.

Note that the relative file specification FileSpec may also be of the form Path(FileSpec), in which case the absolute file name of the file FileSpec in one of the directories designated by Path is returned (see the description of each phase below).

Phase 1
This phase translates the relative file specification given by FileSpec into the corresponding absolute file name. See Input Output, for a description of syntactic rewriting. The rewrite is done wrt. the value of the relative_to option. There can be more than one solution, in which case the outfile becomes the solutions in the order they are generated. If the succeeding phase fails, and there are no more solutions, an existence exception is raised.
Phase 2
See the ignore_underscores option.
Phase 3
See the extensions and file_type options.
Phase 4
See the access option.

Comments:

To check whether the file my_text exists in the home directory, with one of the extensions `.text' or `.txt', and is both writable and readable:

          | ?- absolute_file_name('~/my_text', File,
                                  [extensions(['.text','.txt']),
                                  access([read,write])]).
     

To check if the Prolog file same_functor exists in some library, and also check if it exists under the name samefunctor:

          | ?- absolute_file_name(library(same_functor), File,
                                  [file_type(source), access(exist),
                                   ignore_underscores(true)]).
     

file_search_path(+Path,-Expansion) hook
user:file_search_path(+Path,-Expansion)
Specifies how to rewrite compound file specifications to atomic file names, as described in Input Output. Path should be an atom and Expansions a file name. The predicate may succeed nondeterminately in this search for an atomic file name.

The predicate is undefined at startup, but behaves as if it were a dynamic, multifile predicate with the following clauses. See State Info for more info on the Prolog flag host_type. The environment variables SP_APP_DIR and SP_RT_DIR expand respectively to the absolute path of the directory that contains the executable and the directory that contains the SICStus run-time.

          file_search_path(library, Path) :-
                  library_directory(Path).
          file_search_path(system, Platform) :-
                  prolog_flag(host_type, Platform).
          file_search_path(application, '$SP_APP_DIR').
          file_search_path(runtime, '$SP_RT_DIR').
     

library_directory(-Directory) hook
user:library_directory(-Directory)
Specifies a directory to be searched when a file specification of the form library(Name) is used. The predicate is undefined at startup, but behaves as if it were a dynamic, multifile predicate with a single clause defining the location of the Prolog library. The initial value is the same as the value of the environment variable SP_LIBRARY_DIR. The predicate may succeed nondeterminately in this search for a library directory.
open(+FileName,+Mode,-Stream) ISO
open(+FileName,+Mode,-Stream,+Options) ISO
If FileName is a valid file specification, the file that it denotes is opened in mode Mode (invoking the UNIX function fopen) and the resulting stream is unified with Stream. Mode is one of:
read
Open the file for input.
write
Open the file for output. The file is created if it does not already exist, the file will otherwise be truncated.
append
Open the file for output. The file is created if it does not already exist, the file will otherwise be appended to.

If FileName is an integer, it is assumed to be a file descriptor passed to Prolog from C. The file descriptor is connected to a Prolog stream (invoking the POSIX function fdopen) which is unified with Stream.

Options is a list of zero or more of:

type(+T)
Specifies whether the stream is a text or binary stream. Default is text.
reposition(+Boolean)
Specifies whether repositioning is required for the stream (true), or not (false). The latter is the default.
alias(+A)
Specifies that the atom A is to be an alias for the stream.
eof_action(+Action)
Specifies what action is to be taken when the end of stream has already been reported (by returning -1 or end_of_file), and a further attempt to input is made. Action can have the following values:
error
An exception is raised. This is the default.
eof_code
An end of stream indicator (-1 or end_of_file) is returned again.
reset
The stream is considered not to be at end of stream and another attempt is made to input from it.

wcx(Wcx)
Specifies to pass the term Wcx to the wide character extension component; see Prolog Level WCX Features.

close(+X) ISO
close(+X, +Options) ISO
If X is a stream or alias, the stream is closed. If X is the name of a file opened by see/1 or tell/1, the corresponding stream is closed. Options is a list possibly containing the following element:
force(Boolean)
Specifies whether SICStus Prolog is to close the stream forcefully, even in the presence of errors (true), or not (false). The latter is the default. Currently this option has no effect.

current_input(?Stream) ISO
Stream is the current input stream. The current input stream is also accessed by the C variable SP_curin.
current_output(?Stream) ISO
Stream is the current output stream. The current output stream is also accessed by the C variable SP_curout.
current_stream(?FileName,?Mode,?Stream)
Stream is a stream that was opened in mode Mode and that is connected to the absolute file name Filename (an atom) or to the file descriptor Filename (an integer). This predicate can be used for enumerating all currently open streams through backtracking.
set_input(+Stream) ISO
Sets the current input stream to Stream.
set_output(+Stream) ISO
Sets the current output stream to Stream.
flush_output ISO
flush_output(+Stream) ISO
Flushes all internally buffered characters or bytes for Stream to the operating system.
open_null_stream(-Stream)
Opens a text output stream. Everything written to this stream will be thrown away.
character_count(+Stream,?N)
N is the number of characters read/written on text stream Stream. The count is reset by set_stream_position/2.
byte_count(+Stream,?N)
N is the number of bytes read/written on stream Stream. Meaningful for both binary and text streams. In the latter case it will differ from the number returned by character_count/2 in the presence of wide characters. The count is reset by set_stream_position/2.
line_count(+Stream,?N)
N is the number of lines read/written on text stream Stream. The count is reset by set_stream_position/2.
line_position(+Stream,?N)
N is the number of characters read/written on the current line of text stream Stream. The count is reset by set_stream_position/2.
stream_position(+Stream,?Position)
Position is a term representing the current stream position of Stream. This operation is available for any Prolog stream. You can retrieve certain data from a stream position term using stream_position_data/3.
stream_position_data(?Field, +Pos, ?Data)
The Field field of the Pos term is Data. Pos is a stream position; Field is one of: line_count, character_count, line_position, byte_count.
stream_property(?Stream, ?Property)) ISO
Stream Stream has property Property. Enumerates through backtracking all currently open streams, including the standard input/output/error streams, and all their properties.

Property can be one of the following:

file_name(?F)
F is the file name associated with the Stream.
mode(?M)
Stream has been opened in mode M.
input
Stream is an input stream.
output
Stream is an output stream.
alias(?A)
Stream has an alias A.
position(?P)
P is a term representing the current stream position of Stream. Same as stream_position(Stream, P).
end_of_stream(?E)
E describes the position of the input stream Stream, with respect to the end of stream. If not all characters have been read, then E is unified with not; otherwise, (all characters read) but no end of stream indicator (-1 or end_of_file) was reported yet, then E is unified with at; otherwise, E is unified with past.
eof_action(?A)
A is the end-of-file action applicable to Stream, cf. the eof_action option of open/4.
type(?T)
Stream is of type T.
wcx(?Wcx)
Wide character extension information Wcx was supplied at opening Stream; see Prolog Level WCX Features.

set_stream_position(+Stream,+Position) ISO
Position is a term representing a new stream position of Stream, which is then set to the new position. This operation is only available for Prolog streams connected to “seekable devices” (disk files, usually). If the option reposition(true) was supplied at the successful opening of the stream, then set_stream_position/2 is guaranteed to be successful.
seek(+Stream,+Offset,+Method,-NewLocation)
True if the stream Stream can be set to the byte offset Offset relative to Method, and NewLocation is the new byte offset from the beginning of the file after the operation. Method must be one of:
bof
Seek from the beginning of the file stream.
current
Seek from the current position of the file stream.
eof
Seek from the end of the file stream.

This operation is only available for Prolog streams connected to “seekable devices” (disk files, usually) and is an interface to the stdio functions fseek and ftell. After applying this operation, the character count, line count and line position aspects of the stream position of Stream will be undefined.

at_end_of_stream ISO
at_end_of_stream(+Stream) ISO
The end of stream has been reached for the input stream Stream. An input stream reaches end of stream when all characters (except `EOF', i.e. -1) of the stream have been read. These predicates peek ahead for next input character if there is no character available on the buffer of Stream. Unless the stream is to be treated as connected to the terminal (see SP_force_interactive(), Initializing the Prolog Engine), a stream remains at end of stream after `EOF' has been read, and any further attempt to read from the stream will raise an existence error (see Exception).
at_end_of_line
at_end_of_line(+Stream)
The end of stream or end of line has been reached for the input stream Stream. An input stream reaches end of line when all the characters except <LFD> of the current line have been read. These predicates peek ahead for next input character if there is no character available on the buffer of Stream.
fileerrors obsolescent
Undoes the effect of nofileerrors/0.
nofileerrors obsolescent
After a call to this predicate, failure to locate or open a file will cause the operation to fail instead of the default action, which is to raise an exception.