Module: sio

set_stream_position/2 — seek to a new position in a stream

ISO Standard Predicate


set_stream_position(Stream_or_Alias, Position)


set_stream_position/2 is used to change the stream position for a stream which is repositionable.

Stream_or_Alias is the stream for which to change the stream position.

Position is a term which represents the new position to set. It takes one of the following forms:


Suppose that the file “test” is comprised of the characters “abcdefgh\n”.

Open and read the first character from the file test.

?- open(test,read,_,[alias(test_alias)]), get_char(test_alias,C).
C = a

Seek to two characters before end of file and get the character at this position.

?- set_stream_position(test_alias,end_of_stream(-2)),
?-_ get_char(test_alias,C).
C = h

Seek to current position minus two and get the character at this position.

?- set_stream_position(test_alias,current_position(-2)),
?-_ get_char(test_alias,C).
C = g

Seek to fourth character in file and get it. Recall that the first character has address 0.

?- set_stream_position(test_alias,3), get_char(test_alias,C).
C = d

Get this same character again by backing up one.

?- set_stream_position(test_alias,current_position(-1)),
?-_ get_char(test_alias,C).
C = d

Get the next character in the stream.

?- get_char(test_alias,C).
C = e

Get the current stream position.

?- stream_property(test_alias,position(P)).
P = 5

Get the current stream position, seek to the beginning of the stream and get that character, then seek back to the old position and get the character at that position.

?- stream_property(test_alias, position(P)),
?-_ set_stream_position(test_alias, beginning_of_stream),
?-_ get_char(test_alias, C1),
?-_ set_stream_position(test_alias, P),
?-_ get_char(test_alias, C2).
P = 5
C1 = a
C2 = f


Stream_or_Alias is a variable

– – – – > instantiation_error

Position is a variable

– – – – > instantiation_error

Stream_or_Alias is neither a variable nor a stream descriptor nor an alias

– – – – > domain_error(stream_position, Position)

Position is neither a variable nor a stream position

– – – – > domain_error(stream_position, Position)

Stream_or_Alias is not associated with an open stream

– – – – > existence_error(stream, Stream_or_Alias)

Stream_or_Alias has stream property reposition(false)

– – – – > permission_error(reposition, stream, Stream_or_Alias)


As the example above demonstrates, set_stream_position/2 may be used when used in conjunction with stream_property/2. Typically a program will get the current position using stream_property/2 and later set the stream position using this saved position.