12.9 Foreign access to Prolog IO streams
All Application Manual Name SummaryHelp

  • Documentation
    • Reference manual
      • Foreign Language Interface
        • Foreign access to Prolog IO streams
          • Get IO stream handles
          • Creating an IO stream
          • Interacting with foreign streams
            • Sset_timeout()
            • Sunit_size()
            • Sputc()
            • Sgetc()
            • Sfgetc()
            • Sungetc()
            • Sputcode()
            • Sgetcode()
            • Speekcode()
            • Sputw()
            • Sgetw()
            • Sfread()
            • Sfwrite()
            • Sfeof()
            • Sfpasteof()
            • Ssetlocale()
            • Sflush()
            • Ssize()
            • Sseek()
            • Sseek64()
            • Stell()
            • Stell64()
            • Sclose()
            • Sgcclose()
            • Sfgets()
            • Sgets()
            • Sread_pending()
            • Spending()
            • Sfputs()
            • Sputs()
            • Sfprintf()
            • SfprintfX()
            • Sprintf()
            • Svprintf()
            • Ssprintf()
            • Ssnprintf()
            • SsnprintfX()
            • Svsprintf()
            • Svsnprintf()
            • Sdprintf()
            • SdprintfX()
            • Svdprintf()
            • Slock()
            • StryLock()
            • Sunlock()
            • Sfileno()
            • Swinsock()
            • Sclosehook()
            • Sset_filter()
            • Ssetbuffer()
            • Writing Prolog terms to foreign streams
          • Foreign stream error handling
          • Foreign stream encoding
          • Foreign stream line endings
          • Foreign stream position information
          • Support functions for blob save/load
    • Packages

12.9.3 Interacting with foreign streams

int Sset_timeout(IOSTREAM *s, int milliseconds)
Set the timeout on an input stream to milliseconds. If this value is non-negative the the poll() or select() API is used to wait until input is available. If no input is available within the specified time an error is raised on the stream.
int Sunit_size()
Returns the size of a code unit in bytes depending on the stream's encoding. This returns 2 for the encodings ENC_UNICODE_BE and ENC_UNICODE_LE, sizeof(wchar_t) for ENC_WCHAR and 1 for all other encodings (including multibyte encodings such as ENC_UTF8.
int Sputc(int c, IOSTREAM *s)
Emit a byte to s. Flushes the buffer on \n when in SIO_LBUF buffering mode and updates the stream position information if enabled (SIO_RECORDPOS). Returns 0 on success, -1 on error.
int Sgetc(IOSTREAM *s)
Read a byte from s. Fills the input buffer if buffering is enabled and the buffer is empty. Updates the stream position information if enabled (SIO_RECORDPOS). Returns -1 on end of file or error. Use Sferror() or Sfeof() to distinguish end of file from an error. This is a C macro.
int Sfgetc(IOSTREAM *s)
Function equivalent to Sgetc().
int Sungetc(int c, IOSTREAM *s)
Put a byte back into the input buffer. Returns -1 if this is not possible. Deprecated. New code should use Speekcode() because that reliably maintains the position information on the stream.
int Sputcode(int c, IOSTREAM *s)
Emit a Unicode code point to s. This function also performs newline encoding (see section 12.9.6). If the encoding of s cannot represent c, the behaviour depends on the the following flags. Only one of these flags may be enabled. If none of these flags is enabled an error is raised and the function returns -1.
SIO_REPXML
Emit as XML character entity, e.g. ႒
SIO_REPPL
Emit as ISO escape, e.g., \x4242\
SIO_REPPLU
Emit as Unicode escape, e.g., \u4242 or \U42424242

Updates the stream position information if enabled (SIO_RECORDPOS)

int Sgetcode(IOSTREAM *s)
Read a Unicode code point from s. If it detects an invalid multibyte character a warning is emitted and the code point 0xfffd is returned. Other errors and end-of-file return -1; Use Sferror() or Sfeof() to distinguish end of file from an error.
int Speekcode(IOSTREAM *s)
As Sgetcode(), but leaves the character in the input buffer and does not update the stream position. Returns -1 if the stream is not buffered (SIO_NBUF).
int Sputw(int w, IOSTREAM *s)
int Sgetw(IOSTREAM *s)
Reads/writes an integer in native byte order. Deprecated.
size_t Sfread(void *data, size_t size, size_t elems, IOSTREAM *s)
size_t Sfwrite(const void *data, size_t size, size_t elems, IOSTREAM *s)
Emulations of the POSIX fread() and fwrite() calls for Prolog streams. These functions read or write elems objects of size size and return the number of objects successfully read or written. Data exchange is binary (even if the stream is in text mode) and unlike read() and write(), these functions keep reading or writing until end-of-file (for Sfread()) or an error.
int Sfeof(IOSTREAM *s)
Returns non-zero if the stream is at the end. It performs the following checks: (1) test the SIO_FEOF flag, (2) test whether the buffer is non-empty, (3) fill the buffer and return non-zero if the Sread_function() returned 0 (zero).
int Sfpasteof(IOSTREAM *s)
Returns non-zero when a read operation was performed after signalling end-of-file. On other words, reaching end-of-file first triggers Sfeof() and after another read triggers Sfpasteof().
int Ssetlocale(IOSTREAM *s, struct PL_locale *new_loc, struct PL_locale **old_loc)
Change the locale associated with a stream. The current system does not provide a public C API for dealing with Prolog locale objects. See section 4.23.
int Sflush(IOSTREAM *s)
Flush buffered output, returning 0 on success and -1 after a (write) error occurred. Calls Scontrol_function() using the action SIO_FLUSHOUTPUT after the buffer was successfully written.
int64_t Ssize(IOSTREAM *s)
Returns the size in bytes of the object associated to the stream or -1 if this is not known.
int Sseek(IOSTREAM *s, long pos, int whence)
Deprecated - use Sseek64() instead because some platforms define long as 32-bits.
int Sseek64(IOSTREAM *s, int64_t pos, int whence)
Reposition the file pointer in the object associated to s, returning 0 on success and -1 otherwise. If the stream is buffered and position information is maintained these functions readjust the buffer information if possible. Otherwise they call Sseek64_function() or Sseek_function() as a fallback iff pos can be represented as a C long. Whence is one of SIO_SEEK_SET, SIO_SEEK_CUR or SIO_SEEK_END, seeking relative to the start, current position or end.
long Stell(IOSTREAM *s)
Deprecated - use Stell64() instead because some platforms define long as 32-bits.
int64_t Stell64(IOSTREAM *s)
Return the current position in the stream. This is obtained from the recorded position or based on information from the seek handlers, adjusted with the buffer information.
int Sclose(IOSTREAM *s)
Close the stream. This first locks the stream (see PL_acquire_stream()). When successful it flushes pending output and calls the Sclose_function() hook. Finally, the stream is unlocked and all memory associated to the stream is released. On success, the function returns 0. On failure a Prolog exception is raised and the return value is -1. Regardless of the return value, s becomes invalid after completion of Sclose(). See also Sgcclose().
int Sgcclose(IOSTREAM *s, int flags)
As Sclose(), but intended to be used from the atom garbage collector if a stream is closed because it is garbage. The SWI-Prolog atom garbage collector normally runs in a separate thread and thus may be unable to obtain a lock on s if some thread lost access to the stream while it is locked. For this situation flags may be SIO_CLOSE_TRYLOCK which causes Sgcclose() to return -1 with errno set to EDEADLK if the stream is locked. Alternatively, using SIO_CLOSE_FORCE the stream is closed and released without gaining a lock. This should be safe because the stream is garbage and thus no thread can use the lock.

In addition, Sgcclose() never raises a Prolog exception because Prolog interaction is not allowed from the blob release hook and there is no meaningful way to raise a Prolog exception from this context.

char* Sfgets(char *buf, int n, IOSTREAM *s)
Read a line of input as a sequence of bytes. The buf is n bytes long. On success, buf is returned and contains a 0-terminated C string that ends with a \n character. On end-of-file or an error, NULL is returned. If the input line is longer that n bytes buf is not 0-terminated.
int Sgets(char *buf)
Shorthand for Sfgets(buf, Slinesize, Sinput). Deletes the terminating \n character. Slinesize is a global variable that defines the length of the input buffer. Deprecated.
int Sread_pending(IOSTREAM *s, char *buf, size_t limit, int flags)
Return the data buffered on an input stream. If flags includes SIO_RP_BLOCK, fill the buffer (possibly blocking) if the buffer is empty. Update the stream position information unless flags include SIO_RP_NOPOS. This function effectively provides functionality similar to POSIX read() on a stream. This function is used by read_pending_codes/3.
size_t Spending(IOSTREAM *s)
Return the number of bytes that can be read from s without blocking. If there is buffered input, this is the number of bytes buffered. Otherwise it is the result of the Scontrol_function() using the action SIO_GETPENDING.
int Sfputs(const char *q, IOSTREAM *s)
Emit a 0-terminated C string. The input string q is handled as a sequence of unsigned characters (code points 1 ... 255.
int Sputs(const char *q)
Equivalent to Sfputs(q, Soutput).
int Sfprintf(IOSTREAM *s, const char *fm, ...)
Similar to POSIX fprintf(). This function largely accepts the same % escape sequences. The % character is followed by numeric arguments and modifier characters. The generic format of this is described by the regular expression [+-0 #]*(\d*|\*)(.(\d*|\*))?. Here, + implies right alignment, - left alignment, 0 0-padding and, a space white-space padding and # modified output. The two optional numerical arguments are separated by a full stop and may be * to get them from the argument list. The first numerical argument specifies the field width and the second the precision for floating point numbers.

This sequence is followed by optional type information. For integers this is one of l (long), ll (long long) or z (size_t). For strings this is one of L (ISO Latin 1), U (UTF-8) or W (wchar_t*).

Finally we come to the format specifier. This is one of

  • %
    Emit the % character itself.
  • c
    Emit a Unicode code point.
  • p
    Emit a pointer.
  • d
  • i
    Emit a a signed integer as decimal. The l (long), ll (long long) or z (size_t) denote the size.
  • o
  • u
  • x
  • X
    Emit a a unsigned integer as octal, decimal or hexadecimal.
  • f
  • e
  • E
  • g
  • G
    Emit a double.
  • s
    Emit a 0-terminated string.
  • Unlike the POSIX fprintf(), this function, and the related functions (Svprintf(), etc.) returns the number of characters written. Due to multibyte encodings the number of bytes written can be more. On error, it returns a negative value; in some cases there is extra information (e.g., in errno) but it cannot be relied on.

    Each call to Sfprintf() is atomic in the sense that another thread that calls Sfprintf() on the same stream will block. If you wish to do a series of print statements without any other thread interleaving, you should call PL_acquire_stream() and use its returned IOSTREAM* value, then call PL_release_stream() at the end of the print statements.

    int SfprintfX(IOSTREAM *s, const char *fm, ...)
    Same as Sfprintf() but doesn't have the format-checking attribute, which can trigger compiler warnings if the format does not match the arguments. This is intended for formats that include extended format specifiers such as "%Ws" or "%Us".
    int Sprintf(const char *fm, ...)
    Similar to Sfprintf(), printing to Soutput
    int Svprintf(IOSTREAM *s, const char *fm, va_list args)
    Variadic argument list version of Sfprintf().
    int Ssprintf(char *buf, const char *fm, ...)
    Print to a C string. Deprecated. Use Ssnprintf() instead.
    int Ssnprintf(char *buf, size_t size, const char *fm, ...)
    Print to a C string, emitting a maximum of size bytes while ensuring buf is 0-terminated. The buf is written using UTF-8 encoding. Unlike snprintf(), the return value is the number of logical code points written rather than the number of bytes and if the buffer is too small, -1 is returned rather than the number of bytes that would be written. Future versions may improve compatibility with the POSIX functions.
    int SsnprintfX(char *buf, size_t size, const char *fm, ...)
    Same as Ssnprintf() but doesn't have the format-checking attribute. This is intended for formats that include extended format specifiers such as "%Ws" or "%Us".
    int Svsprintf(char *buf, const char *fm, va_list args)
    Variadic argument list version of Ssprintf(). Deprecated. Use Svsnprintf() instead.
    int Svsnprintf(char *buf, size_t size, const char *fm, va_list args)
    Variadic argument list version of Ssnprintf().
    int Sdprintf(const char *fm, ...)
    Print to Serror. This function should be used for printing debug output from foreign code.
    int SdprintfX(const char *fm, ...)
    Same as Sdprintf() but doesn't have the format-checking attribute. This is intended for formats that include extended format specifiers such as "%Ws" and "%Us".
    int Svdprintf(const char *fm, va_list args)
    Variadic argument list version of Sdprintf().
    int Slock(IOSTREAM *s)
    int StryLock(IOSTREAM *s)
    int Sunlock(IOSTREAM *s)
    Low level versions that perform only the (un)locking part of PL_acquire_stream() and PL_release_stream().
    int Sfileno(IOSTREAM *s)
    If the stream is associated to a POSIX file handle, return this handle. Returns -1 otherwise.
    SOCKET Swinsock(IOSTREAM *s)
    Windows only. If the stream is associated to a Windows socket handle, returns this handle. Otherwise return INVALID_SOCKET
    int Sclosehook(void (*hook)(IOSTREAM *s))
    Register a hook function to be called by Sclose() just before the stream is deallocated. This is used internally to update the Prolog administration of open streams on Sclose().
    int Sset_filter(IOSTREAM *parent, IOSTREAM *filter)
    Register filter as a stream that reads from or writes to the stream parent.
    void Ssetbuffer(IOSTREAM *s, char *buf, size_t size)
    Set the input or output buffer for s to size. The buf argument is either NULL, asking the system to allocate a buffer or points at a buffer of (at least) the indicated size long. The default buffer size is defined by the C macro SIO_BUFSIZE

    12.9.3.1 Writing Prolog terms to foreign streams

    int PL_write_term(IOSTREAM *s, term_t term, int precedence, int flags)
    Write term to s. precedence is the initial operator precedence, typically 1200. flags is a bitwise or of the constants below. These flags map to options for write_term/2.
    PL_WRT_QUOTED
    PL_WRT_IGNOREOPS
    PL_WRT_NUMBERVARS
    PL_WRT_PORTRAY
    PL_WRT_CHARESCAPES
    PL_WRT_NO_CHARESCAPES
    The PL_WRT_NO_CHARESCAPES does not map to a write_term/2 option. If one of PL_WRT_CHARESCAPES or PL_WRT_NO_CHARESCAPES is specified, character escapes are (not) applied. If neither is specified the default depends, like for write/1, on the character_escapes flag on the module user.243Prior to version 9.1.6 the default (no flag) was to escape the quotes and the backslash (\).
    PL_WRT_BACKQUOTED_STRING
    PL_WRT_ATTVAR_IGNORE
    PL_WRT_ATTVAR_DOTS
    PL_WRT_ATTVAR_WRITE
    PL_WRT_ATTVAR_PORTRAY
    PL_WRT_BLOB_PORTRAY
    PL_WRT_NO_CYCLES
    PL_WRT_NEWLINE
    PL_WRT_VARNAMES
    PL_WRT_BACKQUOTE_IS_SYMBOL
    PL_WRT_DOTLISTS
    PL_WRT_BRACETERMS
    PL_WRT_NODICT
    PL_WRT_NODOTINATOM
    PL_WRT_NO_LISTS
    PL_WRT_RAT_NATURAL
    PL_WRT_CHARESCAPES_UNICODE
    PL_WRT_QUOTE_NON_ASCII
    PL_WRT_PARTIAL

    For example, to print a term to user_error as the toplevel does, use

        PL_write_term(Suser_error, t, 1200,
                      PL_WRT_QUOTED|PL_WRT_PORTRAY|
                      PL_WRT_VARNAMES|PL_WRT_NEWLINE)