[ Character I/O | Reference Manual | Alphabetic Index ]

# read_string(+Stream, ?Length, -String)

Reads a string from Stream up to a specified length

Stream
  Stream handle or alias (atom)
Length
  Integer or variable.
String
  Variable or String.

## Description

A string of Length characters is read from the input stream Stream. If Length is uninstantiated, the whole stream is consumed and Length is unified with the number of characters read.

If the stream contains less than Length characters, they are all read (in this case, use string_length/2 to determine the number of characters actually read).

On end-of-file, the empty string with length 0 is returned.

Backward compatibility note: before ECLiPSe 7.0, read_string(D,L,S) was a shorthand for read_string(input,D,L,S). New code should use read_string/3 for reading length-limited strings, and read_string/5 for reading character-delimited strings (compatible with SWI Prolog).

### Modes and Determinism

- read_string(+, +, -) is det
- read_string(+, -, -) is det

### Exceptions

(4) instantiation fault
  Stream is a non instantiated.
(5) type error
  Length is a non-integer number.
(5) type error
  String is not a variable or a string.
(24) number expected
  Length is not a variable or number.
(190) end of file reached
  End of file was encountered before reading any character.
(192) illegal stream mode
  Stream is not an input stream.
(193) illegal stream specification
  Stream is an illegal stream specification.
(198) reading past the file end
  Trying to read even after the error 190 was raised.

## Examples

         % read fixed length chunks (while possible)
         ?- open(string("abcde"), read, S),
            read_string(S, 3, String1),
            read_string(S, 3, String2),
            read_string(S, 3, String3).
        String1 = "abc"
        String2 = "de"
        String3 = ""

        % read all
        ?- open(string("abcde"), read, S),
           read_string(S, Len, String).
        Len = 5
        String = "abcde"

        % read/write all
        copy_file(File1, File2) :-
            open(File1, read, In),
            open(File2, write, Out),
            read_string(In, _Length, Content),
            write(Out, Content),
            close(In),
            close(Out).

## See Also

get_char / 2, read_string / 5, read_token / 3, open / 3