# 9. I/O

  ## Class Stdio.File

    Description

      This is the basic I/O object, it provides socket and pipe communication as well as file access. It does not buffer reads and writes by default, and provides no line-by-line reading, that is done with `Stdio.FILE` object.

    Note

      The file or stream will normally be closed when this object is destructed (unless there are more objects that refer to the same file through use of `assign` or `dup`). Objects do not contain cyclic references in themselves, so they will be destructed timely when they run out of references.

    See also

      `Stdio.FILE`

    Method assign

      ``int` assign(`File`|`Fd` `o`)`

    Description

      This function takes a clone of Stdio.File and assigns all variables of this file from it. It can be used together with `dup()` to move files around.

    See also

      `dup()`

    Method async_connect

      ``int` async_connect(`string` `host`, `int`|`string` `port`, `function`(`int`, `mixed` ... :`void`) `callback`, `mixed` ... `args`)`

    Description

      Open a TCP/IP connection asynchronously.

      This function is similar to `connect()`, but works asynchronously.

    Parameter `host`

      Hostname or IP to connect to.

    Parameter `port`

      Port number or service name to connect to.

    Parameter `callback`

      Function to be called on completion. The first argument will be `1` if a connection was successfully established, and `0` (zero) on failure. The rest of the arguments to `callback` are passed verbatim from `args`.

    Parameter `args`

      Extra arguments to pass to `callback`.

    Returns

      Returns `0` on failure, and `1` if `callback` will be used.

    Note

      The socket may be opened with `open_socket()` ahead of the call to this function, but it is not required.

    Note

      This object is put in callback mode by this function. For `callback` to be called, the backend must be active. See e.g. `set_read_callback` for more details about backends and callback mode.

    Note

      The socket will be in nonblocking state if the connection is successful, and any callbacks will be cleared.

    See also

      `connect()`, `open_socket()`, `set_nonblocking()`

    Method close

      ``int` close()`
      ``int` close(`string` `direction`)`

    Description

      Close the file. Optionally, specify "r", "w" or "rw" to close just the read, just the write or both read and write directions of the file respectively.

      An exception is thrown if an I/O error occurs.

    Returns

      Nonzero is returned if the file wasn't open in the specified direction, zero otherwise.

    Note

      This function will not call the `close_callback`.

    See also

      `open`, `open_socket`

    Method connect

      ``variant` `int` connect(`string` `host`, `int(0..)`|`string` `port`)`
      ``variant` `int` connect(`string` `host`, `int(0..)`|`string` `port`, `string` `client`, `int(0..)`|`string` `client_port`)`
      ``variant` `string` connect(`string` `host`, `int(0..)`|`string` `port`, `string` `data`)`
      ``variant` `string` connect(`string` `host`, `int(0..)`|`string` `port`, `int(0..0)`|`string` `client`, `int(0..)`|`string` `client_port`, `string` `data`)`

    Description

      Open a TCP/IP connection to the specified destination.

      In nonblocking mode, success is indicated with the write-callback, and failure with the close-callback or the read_oob-callback.

      The `host` argument is the hostname or IP number of the remote machine.

      A local IP and port can be explicitly bound by specifying `client` and `client_port`.

      If the `data` argument is included the socket will use TCP_FAST_OPEN if posible. In this mode the the function will return the part of the data that has not been sent to the remote server yet instead of 1 (you will have to use `write` to send this data).

      Note that TCP_FAST_OPEN requires server support, the connection might fail even though the remote server exists. It might be advicable to retry without TCP_FAST_OPEN (and remember this fact)

    Returns

      This function returns 1 or the remaining `data` for success, 0 otherwise.

    Note

      In nonblocking mode `0` (zero) may be returned and `errno()` set to `EWOULDBLOCK` or `WSAEWOULDBLOCK`.

      This should not be regarded as a connection failure. In nonblocking mode you need to wait for a write or close callback before you know if the connection failed or not.

    See also

      `query_address()`, `async_connect()`, `connect_unix()`

    Method connect_unix

      ``int` connect_unix(`string` `path`)`

    Description

      Open a UNIX domain socket connection to the specified destination.

    Returns

      Returns `1` on success, and `0` on failure.

    Note

      Nonblocking mode is not supported while connecting

    Method create

      `Stdio.File Stdio.File()`
      `Stdio.File Stdio.File(`string` `filename`)`
      `Stdio.File Stdio.File(`string` `filename`, `string` `mode`)`
      `Stdio.File Stdio.File(`string` `filename`, `string` `mode`, `int` `mask`)`
      `Stdio.File Stdio.File(`string` `descriptorname`)`
      `Stdio.File Stdio.File(`int` `fd`)`
      `Stdio.File Stdio.File(`int` `fd`, `string` `mode`)`

    Description

      There are four basic ways to create a Stdio.File object. The first is calling it without any arguments, in which case the you'd have to call `open()`, `connect()` or some other method which connects the File object with a stream.

      The second way is calling it with a `filename` and open `mode`. This is the same thing as cloning and then calling `open()`, except shorter and faster.

      The third way is to call it with `descriptorname` of `"stdin"`, `"stdout"` or `"stderr"`. This will open the specified standard stream.

      For the advanced users, you can use the file descriptors of the systems (note: emulated by pike on some systems - like NT). This is only useful for streaming purposes on unix systems. This is not recommended at all if you don't know what you're into. Default `mode` for this is `"rw"`.

    Note

      Open mode will be filtered through the system UMASK. You might need to use `chmod()` later.

    See also

      `open()`, `connect()`, `Stdio.FILE`,

    Method dup

      ``File` dup()`

    Description

      This function returns a clone of Stdio.File with all variables copied from this file.

    Note

      All variables, even `id`, are copied.

    See also

      `assign()`

    Method errno

      ``int` errno()`

    Description

      Returns the error code for the last command on this file. Error code is normally cleared when a command is successful.

    Inherit Fd

      ``optional` inherit Fd : Fd`

    Method line_iterator

      ``String.SplitIterator`|`LineIterator` line_iterator(`int`|`void` `trim`)`

    Description

      Returns an iterator that will loop over the lines in this file. If trim is true, all `'\r'` characters will be removed from the input.

    Method open

      ``int` open(`string` `filename`, `string` `mode`)`
      ``int` open(`string` `filename`, `string` `mode`, `int` `mask`)`

    Description

      Open a file for read, write or append. The parameter `mode` should contain one or more of the following letters:

      ``"r"`` | Open file for reading.
      ``"w"`` | Open file for writing.
      ``"a"`` | Open file for append (use with `"w"`).
      ``"t"`` | Truncate file at open (use with `"w"`).
      ``"c"`` | Create file if it doesn't exist (use with `"w"`).
      ``"x"`` | Fail if file already exists (use with `"c"`).

      `mode` should always contain at least one of the letters `"r"` or `"w"`.

      The parameter `mask` is protection bits to use if the file is created. Default is `0666` (read+write for all in octal notation).

    Returns

      This function returns `1` for success, `0` otherwise.

    See also

      `close()`, `create()`

    Method open_socket

      ``int` open_socket(`int`|`string`|`void` `port`, `string`|`void` `address`, `int`|`string`|`void` `family_hint`)`

    Description

      This makes this file into a socket ready for connections. The reason for this function is so that you can set the socket to nonblocking or blocking (default is blocking) before you call `connect()`.

    Parameter `port`

      If you give a port number to this function, the socket will be bound to this port locally before connecting anywhere. This is only useful for some silly protocols like FTP. The port can also be specified as a string, giving the name of the service associated with the port. Pass -1 to not specify a port (eg to bind only to an address).

    Parameter `address`

      You may specify an address to bind to if your machine has many IP numbers.

    Parameter `family_hint`

      A protocol family for the socket can be specified. If no family is specified, one which is appropriate for the address is automatically selected. Thus, there is normally no need to specify it. If you do not want to specify a bind address, you can provide the address as a hint here instead, to allow the automatic selection to work anyway.

    Returns

      This function returns 1 for success, 0 otherwise.

    See also

      `connect()`, `set_nonblocking()`, `set_blocking()`

    Method openat

      ``File` openat(`string` `filename`)`
      ``File` openat(`string` `filename`, `string` `mode`)`
      ``File` openat(`string` `filename`, `string` `mode`, `int` `mask`)`

    Description

      Open a file relative to an open directory.

    See also

      `File.statat()`, `File.unlinkat()`

    Method openpt

      ``int` openpt(`string` `mode`)`

    Description

      Open the master end of a pseudo-terminal pair. The parameter `mode` should contain one or more of the following letters:

      ``"r"`` | Open terminal for reading.
      ``"w"`` | Open terminal for writing.

      `mode` should always contain at least one of the letters `"r"` or `"w"`.

    See also

      `grantpt()`

    Method pipe

      ``File` pipe(`void`|`int` `required_properties`)`

    Description

      This function creates a pipe between the object it was called in and an object that is returned.

    Parameter `required_properties`

      Binary or (`predef::`|()`) of required `PROP_` properties.

      ``PROP_IPC`` | The resulting pipe may be used for inter process communication.
      ``PROP_NONBLOCK`` | The resulting pipe supports nonblocking I/O.
      ``PROP_SHUTDOWN`` | The resulting pipe supports shutting down transmission in either direction (see `close()`).
      ``PROP_BUFFERED`` | The resulting pipe is buffered (usually 4KB).
      ``PROP_BIDIRECTIONAL`` | The resulting pipe is bi-directional.
      ``PROP_SEND_FD`` | The resulting pipe might support sending of file descriptors (see `send_fd()` and `receive_fd()` for details).
      ``PROP_TTY`` | The resulting pipe is a pseudo-tty.
      ``PROP_REVERSE`` | The resulting pipe supports communication "backwards" (but not necessarily "forwards", see `PROP_BIDIRECTIONAL`).

      The default is `PROP_NONBLOCK|PROP_BIDIRECTIONAL`.

      If `PROP_BIDIRECTIONAL` isn't specified, the read-end is this object, and the write-end is the returned object (unless `PROP_REVERSE` has been specified, in which case it is the other way around).

      The two ends of a bi-directional pipe are indistinguishable.

      For `PROP_TTY` the returned object is the slave (unless `PROP_REVERSE` has been specified).

      If the File object this function is called in was open to begin with, it will be closed before the pipe is created.

    Note

      Calling this function with an argument of `0` is not the same as calling it with no arguments.

    See also

      `Process.create_process()`, `send_fd()`, `receive_fd()`, `PROP_IPC`, `PROP_NONBLOCK`, `PROP_SEND_FD`, `PROP_SHUTDOWN`, `PROP_BUFFERED`, `PROP_REVERSE`, `PROP_BIDIRECTIONAL`, `PROP_TTY`

    Method query_buffer_mode

      ``array`(`Stdio.Buffer`|`int(0..0)`) query_buffer_mode()`

    Description

      Get the active input and output buffers that have been set with `set_buffer_mode()` (if any).

    Returns

      Returns an array with two elements:

      Array
      ``Stdio.Buffer` `0`` | The current input buffer.
      ``Stdio.Buffer` `1`` | The current output buffer.

    See also

      `set_buffer_mode()`

    Method query_read_callback
    Method query_write_callback
    Method query_read_oob_callback
    Method query_write_oob_callback
    Method query_close_callback
    Method query_callbacks

      ``read_callback_t` query_read_callback()`
      ``write_callback_t` query_write_callback()`
      ``function`(`mixed`, `string`:`int`) query_read_oob_callback()`
      ``function`(`mixed`:`int`) query_write_oob_callback()`
      ``function`(`mixed`:`int`) query_close_callback()`
      ``array`(`function`(`mixed`, `void`|`string`:`int`)) query_callbacks()`

    Description

      These functions return the currently installed callbacks for the respective events.

      `query_callbacks` returns the callbacks in the same order as `set_callbacks` and `set_nonblocking` expect them.

    See also

      `set_nonblocking()`, `set_read_callback`, `set_write_callback`, `set_read_oob_callback`, `set_write_oob_callback`, `set_close_callback`, `set_callbacks`

    Method query_id

      ``mixed` query_id()`

    Description

      This function returns the `id` that has been set with `set_id()`.

    See also

      `set_id()`

    Method read

      ``string(8bit)` read(`int`|`void` `nbytes`, `bool`|`void` `not_all`)`

    Description

      Read (optionally buffered) data from a file or a stream.

      Proxy function for `Fd::read()`, that adds support for the buffering configured by `set_buffer_mode()`

    See also

      `read_function()`, `write()`, `Fd::read()`

    Method read_function

      ``function`(:`string`) read_function(`int` `nbytes`)`

    Description

      Returns a function that when called will call `read` with nbytes as argument. Can be used to get various callback functions, eg for the fourth argument to `String.SplitIterator`.

    Method send_fd

      ``void` send_fd(`File`|`Fd` `file`)`

    Method set_blocking

      ``void` set_blocking()`

    Description

      This function clears all callbacks and sets a stream to blocking mode. i.e. reading, writing and closing will wait until data has been transferred before returning.

    Note

      The callbacks are cleared and blocking mode is set in one atomic operation, so no callback gets called in between if the backend is running in another thread.

      Even so, if the stream is in callback mode (i.e. if any callbacks are installed) then only the backend thread can use this function reliably; it might otherwise already be running in a callback which is about to call e.g. `write` when the stream becomes blocking.

    See also

      `set_nonblocking()`, `set_nonblocking_keep_callbacks()`, `set_blocking_keep_callbacks()`

    Method set_nonblocking_keep_callbacks
    Method set_blocking_keep_callbacks

      ``void` set_nonblocking_keep_callbacks()`
      ``void` set_blocking_keep_callbacks()`

    Description

      Toggle between blocking and nonblocking, without changing the callbacks.

    See also

      `set_nonblocking()`, `set_blocking()`

    Method set_buffer_mode

      ``void` set_buffer_mode(`Stdio.Buffer`|`int(0..0)` `in`, `Stdio.Buffer`|`int(0..0)` `out`)`

    Description

      Toggle the file to Buffer mode.

      In this mode reading and writing will be done via Buffer objects, in the directions you included buffers.

    Parameter `in`

      Input buffer.

    Parameter `out`

      Output buffer.

    Note

      Normally you call `write` to re-trigger the write callback if you do not output anything in it (which will stop it from re-occuring again).

      This will work with buffered output mode as well, but simply adding more data to the output buffer will work as well.

    See also

      `get_buffer_mode()`

    Method set_callbacks

      ``void` set_callbacks(`read_callback_t`|`void` `read_cb`, `write_callback_t`|`void` `write_cb`, `void`|`function`(`mixed`:`int`) `close_cb`, `void`|`function`(`mixed`, `string`:`int`) `read_oob_cb`, `void`|`function`(`mixed`:`int`) `write_oob_cb`)`

    Description

      Installs all the specified callbacks at once. Use `UNDEFINED` to keep the current setting for a callback.

      Like `set_nonblocking`, the callbacks are installed atomically. As opposed to `set_nonblocking`, this function does not do anything with the stream, and it doesn't even have to be open.

    See also

      `set_read_callback`, `set_write_callback`, `set_read_oob_callback`, `set_write_oob_callback`, `set_close_callback`, `query_callbacks`

    Method set_read_callback
    Method set_write_callback
    Method set_read_oob_callback
    Method set_write_oob_callback
    Method set_close_callback
    Method set_fs_event_callback

      ``void` set_read_callback(`function`(`mixed`, `string`:`int`) `read_cb`)`
      ``void` set_read_callback(`function`(`mixed`, `Buffer`:`int`) `read_cb`)`
      ``void` set_write_callback(`function`(`mixed`:`int`) `write_cb`)`
      ``void` set_write_callback(`function`(`mixed`, `Buffer`:`int`) `write_cb`)`
      ``void` set_read_oob_callback(`function`(`mixed`, `string`:`int`) `read_oob_cb`)`
      ``void` set_write_oob_callback(`function`(`mixed`:`int`) `write_oob_cb`)`
      ``void` set_close_callback(`function`(`mixed`:`int`) `close_cb`)`
      ``void` set_fs_event_callback(`function`(`mixed`, `int`:`int`) `fs_event_cb`, `int` `event_mask`)`

    Description

      These functions set the various callbacks, which will be called when various events occur on the stream. A zero as argument will remove the callback.

      A `Pike.Backend` object is responsible for calling the callbacks. It requires a thread to be waiting in it to execute the calls. That means that only one of the callbacks will be running at a time, so you don't need mutexes between them.

      Unless you've specified otherwise with the `set_backend` function, the default backend `Pike.DefaultBackend` will be used. It's normally activated by returning `-1` from the `main` function and will then execute in the main thread.

      - When data arrives on the stream, `read_cb` will be called with some or all of that data as the second argument.

        If the file is in buffer mode, the second argument will be a Buffer.

        This will always be the same buffer, so data you do not use in one read callback can be simply left in the buffer, when new data arrives it will be appended

      - When the stream has buffer space over for writing, `write_cb` will be called so that you can write more data to it.

        This callback is also called after the remote end of a socket connection has closed the write direction. An attempt to write data to it in that case will generate a `System.EPIPE` errno. If the remote end has closed both directions simultaneously (the usual case), Pike will first attempt to call `close_cb`, then this callback (unless `close_cb` has closed the stream).

        If the file is in buffer mode, the second argument will be a Buffer.

        You should add data to write to this buffer.

      - When out-of-band data arrives on the stream, `read_oob_cb` will be called with some or all of that data as the second argument.

      - When the stream allows out-of-band data to be sent, `write_oob_cb` will be called so that you can write more out-of-band data to it.

        If the OS doesn't separate the write events for normal and out-of-band data, Pike will try to call `write_oob_cb` first. If it doesn't write anything, then `write_cb` will be tried. This also means that `write_oob_cb` might get called when the remote end of a connection has closed the write direction.

      - When an error or an end-of-stream in the read direction occurs, `close_cb` will be called. `errno` will return the error, or zero in the case of an end-of-stream.

        The name of this callback is rather unfortunate since it really has nothing to do with a close: The stream is still open when `close_cb` is called (you might not be able to read and/or write to it, but you can still use things like `query_address`, and the underlying file descriptor is still allocated). Also, this callback will not be called for a local close, neither by a call to `close` or by destructing this object.

        Also, `close_cb` will not be called if a remote close only occurs in the write direction; that is handled by `write_cb` (or possibly `write_oob_cb`).

        Events to `read_cb` and `close_cb` will be automatically deregistered if an end-of-stream occurs, and all events in the case of an error. I.e. there won't be any more calls to the callbacks unless they are reinstalled. This doesn't affect the callback settings - `query_read_callback` et al will still return the installed callbacks.

      If the stream is a socket performing a nonblocking connect (see `open_socket` and `connect`), a connection failure will call `close_cb`, and a successful connect will call either `read_cb` or `write_cb` as above.

      All callbacks will receive the `id` set by `set_id` as first argument.

      If a callback returns `-1`, no other callback or call out will be called by the backend in that round. I.e. the caller of the backend will get control back right away. For the default backend that means it will immediately start another round and check files and call outs anew.

    Parameter `event_mask`

      An event mask specifing bitwise OR of one or more event types to monitor, selected from `Stdio.NOTE_WRITE` and friends.

    Note

      These functions do not set the file nonblocking.

    Note

      Callbacks are also set by `set_callbacks` and `set_nonblocking()`.

    Note

      After a callback has been called, it's disabled until it has accessed the stream accordingly, i.e. the `write_cb` callback is disabled after it's been called until something has been written with `write`, and the `write_oob_cb` callback is likewise disabled until something has been written with `write_oob`. Since the data already has been read when the read callbacks are called, this effect is not noticeable for them.

    Note

      Installing callbacks means that you will start doing I/O on the stream from the thread running the backend. If you are running these set functions from another thread you must be prepared that the callbacks can be called immediately by the backend thread, so it might not be safe to continue using the stream in this thread.

      Because of that, it's useful to talk about "callback mode" when any callback is installed. In callback mode the stream should be seen as "bound" to the backend thread. For instance, it's only the backend thread that reliably can end callback mode before the stream is "handed over" to another thread.

    Note

      Callback mode has nothing to do with nonblocking mode - although the two often are used together they don't have to be.

    Note

      The file object will stay referenced from the backend object as long as there are callbacks that can receive events.

    Bugs

      Setting a close callback without a read callback currently only works when there's no risk of getting more data on the stream. Otherwise the close callback will be silently deregistered if data arrives.

    Note

      fs_event callbacks only trigger on systems that support these events. Currently, this includes systems that use kqueue, such as Mac OS X, and various flavours of BSD.

    See also

      `set_callbacks`, `set_nonblocking()`, `set_id()`, `set_backend`, `query_read_callback`, `query_write_callback`, `query_read_oob_callback`, `query_write_oob_callback`, `query_close_callback`

    Method set_id

      ``void` set_id(`mixed` `id`)`

    Description

      This function sets the `id` of this file. The `id` is mainly used as an identifier that is sent as the first argument to all callbacks. The default `id` is `0` (zero). Another possible use of the `id` is to hold all data related to this file in a mapping or array.

    See also

      `query_id()`

    Method set_nonblocking

      ``void` set_nonblocking(`read_callback_t` `read_callback`, `write_callback_t` `write_callback`, `function`(`mixed`:`int`) `close_callback`)`
      ``void` set_nonblocking(`read_callback_t` `read_callback`, `write_callback_t` `write_callback`, `function`(`mixed`:`int`) `close_callback`, `function`(`mixed`, `string`:`int`) `read_oob_callback`, `function`(`mixed`:`int`) `write_oob_callback`)`
      ``void` set_nonblocking()`

    Description

      This function sets a stream to nonblocking mode and installs the specified callbacks. See the `set_*_callback` functions for details about them. If no arguments are given, the callbacks will be cleared.

    Note

      As opposed to calling the set callback functions separately, this function will set all the callbacks and nonblocking mode atomically so that no callback gets called in between. That avoids races in case the backend is executed by another thread.

    Note

      Out-of-band data was not be supported on Pike 0.5 and earlier, and not on Pike 0.6 through 7.4 if they were compiled with the option `'--without-oob'`.

    See also

      `set_blocking()`, `set_callbacks`, `set_read_callback()`, `set_write_callback()`, `set_read_oob_callback()`, `set_write_oob_callback()`, `set_close_callback()` `set_nonblocking_keep_callbacks()`, `set_blocking_keep_callbacks()`

  ## Class Stdio.FILE

    Description

      `Stdio.FILE` is a buffered version of `Stdio.File`, it inherits `Stdio.File` and has most of the functionality of `Stdio.File`. However, it has an input buffer that allows line-by-line input.

      It also has support for automatic charset conversion for both input and output (see `Stdio.FILE()->set_charset()`).

    Note

      The output part of `Stdio.FILE` is currently not buffered.

    Method _get_iterator

      `Stdio.FILE a;
      foreach( a; index; value ) or
      ```protected` `object` _get_iterator()`

    Description

      Returns an iterator that will loop over the lines in this file.

    See also

      `line_iterator()`

    Method getchar

      ``local` `int` getchar()`

    Description

      This function returns one character from the input stream.

    Returns

      Returns the ISO-10646 (Unicode) value of the character.

    Note

      Returns an `int` and not a `string` of length 1.

    Method gets

      ``string` gets(`bool`|`void` `not_all`)`

    Description

      Read one line of input with support for input conversion.

    Parameter `not_all`

      Set this parameter to ignore partial lines at EOF. This is useful for eg monitoring a growing logfile.

    Returns

      This function returns the line read if successful, and `0` if no more lines are available.

    See also

      `ngets()`, `read()`, `line_iterator()`, `set_charset()`

    Inherit file

      `inherit File : file`

    Method line_iterator

      ``object` line_iterator(`int`|`void` `trim`)`

    Description

      Returns an iterator that will loop over the lines in this file. If `trim` is true, all `'\r'` characters will be removed from the input.

    Note

      It's not supported to call this method more than once unless a call to `seek` is done in advance. Also note that it's not possible to intermingle calls to `read`, `gets` or other functions that read data with the line iterator, it will produce unexpected results since the internal buffer in the iterator will not contain sequential file-data in those cases.

    See also

      `_get_iterator()`

    Method ngets

      ``array`(`string`) ngets(`void`|`int(1..)` `n`, `bool`|`void` `not_all`)`

    Description

      Get `n` lines.

    Parameter `n`

      Number of lines to get, or all remaining if zero.

    Parameter `not_all`

      Set this parameter to ignore partial lines at EOF. This is useful for eg monitoring a growing logfile.

    Method openat

      ``FILE` openat(`string` `filename`)`
      ``FILE` openat(`string` `filename`, `string` `mode`)`
      ``FILE` openat(`string` `filename`, `string` `mode`, `int` `mask`)`

    Description

      Same as `Stdio.File()->openat()`, but returns an `Stdio.FILE` object.

    See also

      `Stdio.File()->openat()`

    Method pipe

      ``FILE` pipe(`void`|`int` `flags`)`

    Description

      Same as `Stdio.File()->pipe()`, but returns an `Stdio.FILE` object.

    See also

      `Stdio.File()->pipe()`

    Method printf

      ``int` printf(`string` `format`, `mixed` ... `data`)`

    Description

      This function does approximately the same as: ``write`(`sprintf`(`format`,@`data`))`.

    See also

      `write()`, `sprintf()`

    Method read

      ``string` read(`int`|`void` `bytes`, `void`|`bool` `now`)`

    Description

      Read `bytes` (wide-) characters with buffering and support for input conversion.

    See also

      `Stdio.File()->read()`, `set_charset()`, `unread()`

    Method set_charset

      ``void` set_charset(`string`|`void` `charset`)`

    Description

      Sets the input and output charset of this file to the specified `charset`. If `charset` is 0 or not specified the environment is used to try to detect a suitable charset.

      The default charset if this function is not called is `"ISO-8859-1"`.

    FIXME

      Consider using one of ISO-IR-196 (`"\e%G"` - switch to UTF-8 with return) or ISO-IR-190 (`"\e%/G"` - switch to UTF-8 level 1 no return) or ISO-IR-191 (`"\e%/H"` - switch to UTF-8 level 2 no return) or ISO-IR-192 (`"\e%/I"` - switch to UTF-8 level 3 no return) or ISO-IR-193 (`"\e%/J"` - switch to UTF-16 level 1 no return) or ISO-IR-194 (`"\e%/K"` - switch to UTF-16 level 2 no return) or ISO-IR-195 (`"\e%/L"` - switch to UTF-16 level 3 no return) or ISO-IR-162 (`"\e%/@"` - switch to UCS-2 level 1) or ISO-IR-163 (`"\e%/A"` - switch to UCS-4 level 1) or ISO-IR-174 (`"\e%/C"` - switch to UCS-2 level 2) or ISO-IR-175 (`"\e%/D"` - switch to UCS-4 level 2) or ISO-IR-176 (`"\e%/E"` - switch to UCS-2 level 3) or ISO-IR-177 (`"\e%/F"` - switch to UCS-4 level 3) or ISO-IR-178 (`"\e%B"` - switch to UTF-1) automatically to encode wide strings.

    Method ungets

      ``void` ungets(`string` `s`)`

    Description

      This function puts a line back in the input buffer. The line can then be read with eg `read()`, `gets()` or `getchar()`.

    Note

      The string is autoterminated by an extra line-feed.

    See also

      `read()`, `gets()`, `getchar()`, `unread()`

    Method unread

      ``void` unread(`string` `s`)`

    Description

      This function puts a string back in the input buffer. The string can then be read with eg `read()`, `gets()` or `getchar()`.

    See also

      `read()`, `gets()`, `getchar()`, `ungets()`

    Method write

      ``int` write(`array`(`string`)|`string` `what`, `mixed` ... `fmt`)`

    Description

      Write `what` with support for output_conversion.

    See also

      `Stdio.File()->write()`

  ## Class Stdio.Port

    Description

      Handles listening to socket ports. Whenever you need a bound socket that is open and listens for connections you should use this program.

    Method accept

      ``File` accept()`

    Description

      This function completes a connection made from a remote machine to this port. It returns a two-way stream in the form of a clone of `Stdio.File`. The new file is by initially set to blocking mode.

    See also

      `Stdio.File`

    Method accept

      ``Stdio.File` accept()`

    Description

      Get the first connection request waiting for this port and return it as a connected socket.

      If no connection request is waiting and the port is in nonblocking mode (i.e. an accept callback is installed) then zero is returned. Otherwise this function waits until a connection has arrived.

      In Pike 7.8 and later the returned object is created via `fd_factory()`.

    Note

      In Pike 7.7 and later the resulting file object will be assigned to the same backend as the port object.

    Method bind

      ``int` bind(`int`|`string` `port`, `void`|`function`(:`void`) `accept_callback`, `void`|`string` `ip`, `void`|`string` `reuse_port`)`

    Description

      Opens a socket and binds it to port number on the local machine. If the second argument is present, the socket is set to nonblocking and the callback funcition is called whenever something connects to it. The callback will receive the id for this port as argument and should typically call `accept` to establish a connection.

      If the optional argument `ip` is given, `bind` will try to bind to an interface with that host name or IP number. Omitting this will bind to all available IPv4 addresses; specifying "::" will bind to all IPv4 and IPv6 addresses.

      If the OS supports TCP_FASTOPEN it is enabled automatically.

      If the OS supports SO_REUSEPORT it is enabled if the fourth argument is true.

    Returns

      1 is returned on success, zero on failure. `errno` provides further details about the error in the latter case.

    See also

      `accept`, `set_id`

    Method bind_unix

      ``int` bind_unix(`string` `path`, `void`|`function`(:`void`) `accept_callback`)`

    Description

      Opens a Unix domain socket at the given path in the file system. If the second argument is present, the socket is set to nonblocking and the callback funcition is called whenever something connects to it. The callback will receive the id for this port as argument and should typically call `accept` to establish a connection.

    Returns

      1 is returned on success, zero on failure. `errno` provides further details about the error in the latter case.

    Note

      This function is only available on systems that support Unix domain sockets.

    Note

      `path` had a quite restrictive length limit (~100 characters) prior to Pike 7.8.334.

    See also

      `accept`, `set_id`

    Method close

      ``void` close()`

    Description

      Closes the socket.

    Method create

      `Stdio.Port Stdio.Port()`
      `Stdio.Port Stdio.Port(`int`|`string` `port`)`
      `Stdio.Port Stdio.Port(`int`|`string` `port`, `function`(:`void`) `accept_callback`)`
      `Stdio.Port Stdio.Port(`int`|`string` `port`, `function`(:`void`) `accept_callback`, `string` `ip`)`
      `Stdio.Port Stdio.Port(`"stdin"`)`
      `Stdio.Port Stdio.Port(`"stdin"`, `function`(:`void`) `accept_callback`)`

    Description

      If the first argument is other than `"stdin"` the arguments will be passed to `bind()`.

      When create is called with `"stdin"` as the first argument, a socket is created out of the file descriptor `0`. This is only useful if it actually is a socket to begin with.

    See also

      `bind`

    Method create

      `Stdio.Port Stdio.Port(`int`|`string` `port`, `void`|`function`(:`void`) `accept_callback`, `void`|`string` `ip`)`
      `Stdio.Port Stdio.Port(`"stdin"`, `void`|`function`(:`void`) `accept_callback`)`

    Description

      When called with an int or any string except `"stdin"` as first argument, this function does the same as `bind()` would do with the same arguments.

      When called with `"stdin"` as argument, a socket is created out of the file descriptor 0. This is only useful if that actually IS a socket to begin with.

    See also

      `bind`, `listen_fd`

    Method errno

      ``int` errno()`

    Description

      If the last call done on this port failed, this function will return an integer describing what went wrong. Refer to your unix manual for further information.

    Method fd_factory

      ``protected` `Fd` fd_factory()`

    Description

      Factory creating empty `Fd` objects.

      This function is called by `accept()` when it needs to create a new file.

    Inherit _port

      `inherit _port : _port`

    Method listen_fd

      ``int` listen_fd(`int` `fd`, `void`|`function`(:`void`) `accept_callback`)`

    Description

      This function does the same as `bind`, except that instead of creating a new socket and bind it to a port, it expects the file descriptor `fd` to be an already open port.

    Note

      This function is only for the advanced user, and is generally used when sockets are passed to Pike at exec time.

    See also

      `bind`, `accept`

    Method query_address

      ``string` query_address()`

    Description

      Get the address and port of the local socket end-point.

    Returns

      This function returns the address and port of a socket end-point on the form `"x.x.x.x port"` (IPv4) or `"x:x:x:x:x:x:x:x port"` (IPv6).

      If there is some error querying or formatting the address, `0` (zero) is returned and `errno()` will return the error code.

    Throws

      An error is thrown if the socket isn't bound.

    Method query_backend

      ``Pike.Backend` query_backend()`

    Description

      Return the backend used for the accept callback.

    See also

      `set_backend`

    Method query_fd

      ``int` query_fd()`

    Description

      Returns the file descriptor number associated with this object.

    Method query_id

      ``mixed` query_id()`

    Description

      This function returns the id for this port. The id is normally the first argument to accept_callback.

    See also

      `set_id`

    Method set_backend

      ``void` set_backend(`Pike.Backend` `backend`)`

    Description

      Set the backend used for the accept callback.

    Note

      The backend keeps a reference to this object as long as the port is accepting connections, but this object does not keep a reference to the backend.

    See also

      `query_backend`

    Method set_id

      ``mixed` set_id(`mixed` `id`)`

    Description

      This function sets the id used for accept_callback by this port. The default id is `this_object()`.

    See also

      `query_id`

  ## Class Stdio.UDP

    Description

      UDP (User Datagram Protocol) handling.

    Constant MSG_OOB

      ``constant` Stdio.UDP.`MSG_OOB``

    FIXME

      Document this constant.

    Constant MSG_PEEK

      ``constant` Stdio.UDP.`MSG_PEEK``

    FIXME

      Document this constant.

    Method add_membership

      ``int` add_membership(`string` `group`, `void`|`string` `address`)`

    Description

      Join a multicast group.

    Parameter `group`

      `group` contains the address of the multicast group the application wants to join. It must be a valid multicast address.

    Parameter `address`

      `address` is the address of the local interface with which the system should join to the multicast group. If not provided the system will select an appropriate interface.

      See also the Unix man page for setsocketopt IPPROTO_IP IP_ADD_MEMBERSHIP and IPPROTO_IPV6 IPV6_JOIN_GROUP.

    Note

      The `address` parameter is currently not supported for IPv6.

    Note

      This function did not support IPv6 in Pike 7.8 and earlier.

    See also

      `drop_membership()`

    Method bind

      ``UDP` bind(`int`|`string` `port`, `string`|`void` `address`, `string`|`bool` `no_reuseaddr`)`

    Description

      Binds a port for receiving or transmitting UDP.

    Parameter `port`

      Either a port number or the name of a service as listed in `/etc/services`.

    Parameter `address`

      Local address to bind to.

    Parameter `no_reuseaddr`

      If set to `1`, Pike will not set the `SO_REUSEADDR` option on the UDP port.

    Note

      `SO_REUSEADDR` is never applied when binding a random port (`bind(0)`).

      In general, `SO_REUSEADDR` is not desirable on UDP ports. Unless used for receiving multicast, be sure to never bind a non-random port without setting `no_reuseaddr` to `1`.

    Throws

      Throws error when unable to bind port.

    Method close

      ``bool` close()`

    Description

      Closes an open UDP port.

    Note

      This method was introduced in Pike 7.5.

    Method connect

      ``bool` connect(`string` `address`, `int`|`string` `port`)`

    Description

      Establish an UDP connection.

      This function connects an UDP socket previously created with `Stdio.UDP()` to a remote socket. The `address` is the IP name or number for the remote machine.

    Returns

      Returns `1` on success, `0` (zero) otherwise.

    Note

      If the socket is in nonblocking mode, you have to wait for a write or close callback before you know if the connection failed or not.

    See also

      `bind()`, `query_address()`

    Method drop_membership

      ``int` drop_membership(`string` `group`, `void`|`string` `address`)`

    Description

      Leave a multicast group.

    Parameter `group`

      `group` contains the address of the multicast group the application wants to join. It must be a valid multicast address.

    Parameter `address`

      `address` is the address of the local interface with which the system should join to the multicast group. If not provided the system will select an appropriate interface.

      See also the Unix man page for setsocketopt IPPROTO_IP IP_DROP_MEMBERSHIP and IPPROTO_IPV6 IPV6_LEAVE_GROUP.

    Note

      The `address` parameter is currently not supported for IPv6.

    Note

      This function did not support IPv6 in Pike 7.8 and earlier.

    See also

      `add_membership()`

    Method enable_broadcast

      ``bool` enable_broadcast()`

    Description

      Set the broadcast flag. If enabled then sockets receive packets sent to a broadcast address and they are allowed to send packets to a broadcast address.

    Returns

      Returns `1` on success, `0` (zero) otherwise.

    Note

      This is normally only avalable to root users.

    Method enable_multicast

      ``bool` enable_multicast(`string` `reply_address`)`

    Description

      Set the local device for a multicast socket.

    Parameter `reply_address`

      Local address that should appear in the multicast packets.

      See also the Unix man page for setsocketopt IPPROTO_IP IP_MULTICAST_IF and IPPROTO_IPV6 IPV6_MULTICAST_IF.

    Note

      This function did not support IPv6 in Pike 7.8.

    Method errno

      ``int` errno()`

    Description

      Returns the error code for the last command on this object. Error code is normally cleared when a command is successful.

    Method get_type

      ``array`(`int`) get_type()`

    Description

      Returns socket type and protocol family.

    Inherit UDP

      `inherit _Stdio.UDP : UDP`

    Method query_address

      ``string` query_address()`

    Description

      Returns the local address of a socket on the form "x.x.x.x port". If this file is not a socket, not connected or some other error occurs, zero is returned.

    Method query_backend

      ``Pike.Backend` query_backend()`

    Description

      Return the backend used for the read callback.

    See also

      `set_backend`

    Method query_fd

      ``int` query_fd()`

    Description

      Gets the file descriptor for this UDP port.

    Method read

      ``mapping`(`string`:`int`|`string`) read()`
      ``mapping`(`string`:`int`|`string`) read(`int` `flag`)`

    Description

      Read from the UDP socket.

      Flag `flag` is a bitfield, 1 for out of band data and 2 for peek

    Returns

      mapping(string:int|string) in the form ([ "data" : string received data "ip" : string received from this ip "port" : int ...and this port ])

    See also

      `set_read_callback()`, `MSG_OOB`, `MSG_PEEK`

    Method send

      ``int` send(`string` `to`, `int`|`string` `port`, `string` `message`)`
      ``int` send(`string` `to`, `int`|`string` `port`, `string` `message`, `int` `flags`)`

    Description

      Send data to a UDP socket. The recipient address will be `to` and port will be `port`.

      Flag `flag` is a bitfield, 1 for out of band data and 2 for don't route flag.

    Returns

      The number of bytes that were actually written.

    Method set_backend

      ``void` set_backend(`Pike.Backend` `backend`)`

    Description

      Set the backend used for the read callback.

    Note

      The backend keeps a reference to this object as long as there can be calls to the read callback, but this object does not keep a reference to the backend.

    See also

      `query_backend`

    Method set_blocking

      ``object` set_blocking()`

    Description

      Sets this object to be blocking.

    Method set_buffer

      ``void` set_buffer(`int` `bufsize`, `string` `mode`)`
      ``void` set_buffer(`int` `bufsize`)`

    Description

      Set internal socket buffer.

      This function sets the internal buffer size of a socket or stream.

      The second argument allows you to set the read or write buffer by specifying `"r"` or `"w"`.

    Note

      It is not guaranteed that this function actually does anything, but it certainly helps to increase data transfer speed when it does.

    See also

      `open_socket()`, `accept()`

    Method set_fd

      ``UDP` set_fd(`int` `fd`)`

    Description

      Use the file descriptor `fd` for UDP.

    See also

      `bind`

    Method set_multicast_ttl

      ``int` set_multicast_ttl(`int` `ttl`)`

    Description

      Set the time-to-live value of outgoing multicast packets for this socket.

    Parameter `ttl`

      The number of router hops sent multicast packets should survive.

      It is very important for multicast packets to set the smallest TTL possible. The default before calling this function is 1 which means that multicast packets don't leak from the local network unless the user program explicitly requests it.

      See also the Unix man page for setsocketopt IPPROTO_IP IP_MULTICAST_TTL and IPPROTO_IPV6 IPV6_MULTICAST_HOPS.

    Note

      This function did not support IPv6 in Pike 7.8 and earlier.

    See also

      `add_membership()`

    Method set_nonblocking

      ``UDP` set_nonblocking()`
      ``UDP` set_nonblocking(`function`(`mapping`(`string`:`int`|`string`), `mixed` ... :`void`) `read_cb`, `mixed` ... `extra_args`)`

    Description

      Set this object to nonblocking mode.

      If `read_cb` and `extra_args` are specified, they will be passed on to `set_read_callback()`.

    Returns

      The called object.

    Method set_read_callback

      ``UDP` set_read_callback(`function`(`mapping`(`string`:`int`|`string`), `mixed` ... :`void`) `read_cb`, `mixed` ... `extra_args`)`

    Description

      The `read_cb` function will receive a mapping similar to the mapping returned by `read()`:

      ``"data"` : `string`` | Received data.
      ``"ip"` : `string`` | Data was sent from this IP.
      ``"port"` : `int`` | Data was sent from this port.

    Returns

      The called object.

    See also

      `read()`

    Method set_type

      ``UDP` set_type(`int` `sock_type`)`
      ``UDP` set_type(`int` `sock_type`, `int` `family`)`

    Description

      Sets socket type and protocol family.

    Method wait

      ``bool` wait(`int`|`float` `timeout`)`

    Description

      Check for data and wait max. `timeout` seconds.

    Returns

      Returns `1` if data are ready, `0` (zero) otherwise.

  ## Module Stdio.Terminfo

    Method getFallbackTerm

      ``protected` `Termcap` getFallbackTerm(`string` `term`)`

    Description

      Returns an object describing the fallback terminal for the terminal `term`. This is usually equivalent to `Stdio.Terminfo.getTerm("dumb")`.

    See also

      Stdio.Terminfo.getTerm

    Method getTerm

      ``Termcap` getTerm(`string`|`void` `term`)`

    Description

      Returns an object describing the terminal term. If term is not specified, it will default to `getenv("TERM")` or if that fails to "dumb".

      Lookup of terminal information will first be done in the systems terminfo database, and if that fails in the termcap database. If neither database exists, a hardcoded entry for "dumb" will be used.

    See also

      Stdio.Terminfo.getTerminfo, Stdio.Terminfo.getTermcap, Stdio.getFallbackTerm

    Method getTermcap

      ``Termcap` getTermcap(`string` `term`)`

    Description

      Returns the terminal description object for `term` from the systems termcap database. Returns 0 if not found.

    See also

      Stdio.Terminfo.getTerm, Stdio.Terminfo.getTerminfo

    Method getTerminfo

      ``Terminfo` getTerminfo(`string` `term`)`

    Description

      Returns the terminal description object for `term` from the systems terminfo database. Returns 0 if not found.

    See also

      Stdio.Terminfo.getTerm, Stdio.Terminfo.getTermcap

    Method is_tty

      ``int` is_tty()`

    Description

      Returns 1 if `Stdio.stdin` is connected to an interactive terminal that can handle backspacing, carriage return without linefeed, and the like.

    ## Class Stdio.Terminfo.MetaTerminfoDB

      Description

        `TerminfoDB` that merges several directorys.

      Method create

        `Stdio.Terminfo.MetaTerminfoDB Stdio.Terminfo.MetaTerminfoDB(`array`(`TerminfoDB`|`string`)|`void` `dbs`)`

      Description

        Create a new Meta `TerminfoDB`.

      Parameter `dbs`

        Array with elements in priority order. Elements may be either

        ``TerminfoDB`` | An active `TerminfoDB`.
        ``string`` | A directory that may exist and contain a terminfo database.

      Returns

        If the resulting set of `TerminfoDB`'s is empty, the object will be destructed.

    ## Class Stdio.Terminfo.Termcap

      Description

        Termcap terminal description object.

      Variable aliases

        ``array`(`string`) Stdio.Terminfo.Termcap.aliases`

      Method create

        `Stdio.Terminfo.Termcap Stdio.Terminfo.Termcap(`string` `cap`, `TermcapDB`|`void` `tcdb`, `int`|`void` `maxrecurse`)`

      Inherit TermMachine

        `inherit TermMachine : TermMachine`

      Method tputs

        ``string` tputs(`string` `s`)`

      Description

        Put termcap string

    ## Class Stdio.Terminfo.TermcapDB

      Description

        Termcap database

    ## Class Stdio.Terminfo.Terminfo

      Description

        Terminfo terminal description object

      Variable aliases

        ``array`(`string`) Stdio.Terminfo.Terminfo.aliases`

      Method create

        `Stdio.Terminfo.Terminfo Stdio.Terminfo.Terminfo(`string` `filename`)`

      Inherit TermMachine

        `inherit TermMachine : TermMachine`

      Method tputs

        ``string` tputs(`string` `s`)`

      FIXME

        Document this function

    ## Class Stdio.Terminfo.TerminfoDB

      Description

        Terminfo database for a single directory.

  ## Class Stdio.Readline

    Method add_to_kill_ring

      ``void` add_to_kill_ring(`string` `s`)`

    FIXME

      Document this function

    Method create

      `Stdio.Readline Stdio.Readline(`object`|`void` `infd`, `object`|`string`|`void` `interm`, `object`|`void` `outfd`, `object`|`string`|`void` `outterm`)`

    Description

      Creates a Readline object, that takes input from `infd` and has output on `outfd`.

    Parameter `infd`

      Defaults to `Stdio.stdin`.

    Parameter `interm`

      Defaults to `Stdio.Terminfo.getTerm()`.

    Parameter `outfd`

      Defaults to `infd`, unless `infd` is 0, in which case `outfd` defaults to `Stdio.stdout`.

    Parameter `outterm`

      Defaults to `interm`.

    Method delete

      ``void` delete(`int` `p1`, `int` `p2`)`

    FIXME

      Document this function

    Method delta_history

      ``void` delta_history(`int` `d`)`

    Description

      Changes the line to a line from the history `d` steps from the current entry (0 being the current line, negative values older, and positive values newer).

    Note

      Only effective if you have a history object.

    Method edit

      ``string` edit(`string` `data`, `string`|`void` `local_prompt`, `array`(`string`)|`void` `attrs`)`

    FIXME

      Document this function

    Method enable_history

      ``void` enable_history(`array`(`string`)|`History`|`int` `hist`)`

    FIXME

      Document this function

    Method eof

      ``void` eof()`

    FIXME

      Document this function

    Method get_history

      ``History` get_history()`

    FIXME

      Document this function

    Method get_input_controller

      ``InputController` get_input_controller()`

    Description

      get current input control object

    Returns

      Terminal input controller object

    Method get_output_controller

      ``OutputController` get_output_controller()`

    Description

      get current output control object

    Returns

      Terminal output controller object

    Method get_prompt

      ``string` get_prompt()`

    Description

      Return the current prompt string.

    Method getcursorpos

      ``int` getcursorpos()`

    FIXME

      Document this function

    Method getmark

      ``int` getmark()`

    FIXME

      Document this function

    Method gettext

      ``string` gettext()`

    FIXME

      Document this function

    Method history

      ``void` history(`int` `n`)`

    FIXME

      Document this function

    Method insert

      ``void` insert(`string` `s`, `int` `p`)`

    FIXME

      Document this function

    Method kill

      ``void` kill(`int` `p1`, `int` `p2`)`

    FIXME

      Document this function

    Method kill_ring_yank

      ``string` kill_ring_yank()`

    FIXME

      Document this function

    Method list_completions

      ``void` list_completions(`array`(`string`) `c`)`

    FIXME

      Document this function

    Method message

      ``void` message(`string` `msg`)`

    Description

      Print a message to the output device

    Method newline

      ``string` newline()`

    FIXME

      Document this function

    Method pointmark

      ``array`(`int`) pointmark()`

    FIXME

      Document this function

    Method read

      ``string` read(`string`|`void` `prompt`, `array`(`string`)|`void` `attrs`)`

    FIXME

      Document this function

    Method redisplay

      ``void` redisplay(`int` `clear`, `int`|`void` `nobackup`)`

    FIXME

      Document this function

    Method region

      ``string` region(`int` ... `args`)`

    FIXME

      Document this function

    Method set_blocking

      ``void` set_blocking()`

    FIXME

      Document this function

    Method set_echo

      ``void` set_echo(`int` `onoff`)`

    Description

      Set text echo on or off.

    Parameter `onoff`

      1 for echo, 0 for no echo.

    Method set_nonblocking

      ``void` set_nonblocking(`function`(:`void`) `f`)`

    FIXME

      Document this function

    Method set_prompt

      ``string` set_prompt(`string` `newp`, `array`(`string`)|`void` `newattrs`)`

    Description

      Set the prompt string.

    Parameter `newp`

      New prompt string

    Parameter `newattrs`

      Terminal attributes

    Method setcursorpos

      ``int` setcursorpos(`int` `p`)`

    FIXME

      Document this function

    Method setmark

      ``int` setmark(`int` `p`)`

    FIXME

      Document this function

    Method write

      ``void` write(`string` `msg`, `void`|`int` `word_wrap`)`

    FIXME

      Document this function

    ## Class Stdio.Readline.DefaultEditKeys

      Method backward_char

        ``void` backward_char()`

      Method backward_delete_char

        ``void` backward_delete_char()`

      Method backward_kill_word

        ``void` backward_kill_word()`

      Method backward_word

        ``void` backward_word()`

      Method beginning_of_line

        ``void` beginning_of_line()`

      Method capitalize_word

        ``void` capitalize_word()`

      Method clear_screen

        ``void` clear_screen()`

      Method create

        `Stdio.Readline.DefaultEditKeys Stdio.Readline.DefaultEditKeys(`object` `readline`)`

      Method delete_char

        ``void` delete_char()`

      Method delete_char_or_eof

        ``void` delete_char_or_eof()`

      Method down_history

        ``void` down_history()`

      Method downcase_word

        ``void` downcase_word()`

      Method end_of_line

        ``void` end_of_line()`

      Method forward_char

        ``void` forward_char()`

      Method forward_word

        ``void` forward_word()`

      Method kill_line

        ``void` kill_line()`

      Method kill_region

        ``void` kill_region()`

      Method kill_ring_save

        ``void` kill_ring_save()`

      Method kill_whole_line

        ``void` kill_whole_line()`

      Method kill_word

        ``void` kill_word()`

      Method newline

        ``void` newline()`

      Method quoted_insert

        ``void` quoted_insert()`

      Method redisplay

        ``void` redisplay()`

      Method self_insert_command

        ``void` self_insert_command(`string` `str`)`

      Method set_default_bindings

        ``protected` `void` set_default_bindings()`

      Method set_mark

        ``void` set_mark()`

      Method swap_mark_and_point

        ``void` swap_mark_and_point()`

      Method transpose_chars

        ``void` transpose_chars()`

      Method up_history

        ``void` up_history()`

      Method upcase_word

        ``void` upcase_word()`

      Method yank

        ``void` yank()`

    ## Class Stdio.Readline.History

      Method create

        `Stdio.Readline.History Stdio.Readline.History(`int` `maxhist`, `void`|`array`(`string`) `hist`)`

      Method encode

        ``string` encode()`

      Method finishline

        ``void` finishline(`string` `text`)`

      Method get_history_num

        ``int` get_history_num()`

      Method history

        ``string` history(`int` `n`, `string` `text`)`

      Method initline

        ``void` initline()`

      Method set_max_history

        ``void` set_max_history(`int` `maxhist`)`

    ## Class Stdio.Readline.InputController

      FIXME

        Ought to have support for charset conversion.

      Method bind

        ``function`(:`void`) bind(`string` `k`, `function`(:`void`) `f`)`

      Method bindstr

        ``function`(:`void`) bindstr(`string` `str`, `function`(:`void`) `f`)`

      Method bindtc

        ``function`(:`void`) bindtc(`string` `cap`, `function`(:`void`) `f`)`

      Method create

        `Stdio.Readline.InputController Stdio.Readline.InputController(`object`|`void` `_infd`, `object`|`string`|`void` `_term`)`

      Method disable

        ``int` disable()`

      Method enable

        ``int` enable(`int` ... `e`)`

      Method getbinding

        ``function`(:`void`) getbinding(`string` `k`, `string` `cap`)`

      Method getbindings

        ``mapping`(`string`:`function`(:`void`)) getbindings()`

      Method getbindingstr

        ``function`(:`void`) getbindingstr(`string` `str`)`

      Method getbindingtc

        ``function`(:`void`) getbindingtc(`string` `cap`)`

      Method grabnextkey

        ``void` grabnextkey(`function`(:`void`) `g`)`

      Method isenabled

        ``int` isenabled()`

      Method nullbindings

        ``void` nullbindings()`

      Description

        Clears the bindings.

      Method parsekey

        ``string` parsekey(`string` `k`)`

      Method run_blocking

        ``int` run_blocking()`

      Method set_close_callback

        ``void` set_close_callback(`function`(:`int`) `ccb`)`

      Method unbind

        ``function`(:`void`) unbind(`string` `k`)`

      Method unbindstr

        ``function`(:`void`) unbindstr(`string` `str`)`

      Method unbindtc

        ``function`(:`void`) unbindtc(`string` `cap`)`

    ## Class Stdio.Readline.OutputController

      FIXME

        Ought to have support for charset conversion.

      Method beep

        ``void` beep()`

      Method bol

        ``void` bol()`

      Method check_columns

        ``int` check_columns()`

      Description

        Check and return the terminal width.

      Note

        In Pike 7.4 and earlier this function returned `void`.

      See also

        `get_number_of_columns`

      Method clear

        ``void` clear(`int`|`void` `partial`)`

      Method create

        `Stdio.Readline.OutputController Stdio.Readline.OutputController(`.File`|`void` `_outfd`, `.Terminfo.Termcap`|`string`|`void` `_term`)`

      Method disable

        ``void` disable()`

      Method enable

        ``void` enable()`

      Method erase

        ``void` erase(`string` `s`)`

      Method get_number_of_columns

        ``int` get_number_of_columns()`

      Description

        Returns the width of the terminal.

      Note

        Does not check the width of the terminal.

      See also

        `check_columns`

      Method low_erase

        ``void` low_erase(`int` `n`)`

      Method low_move_backward

        ``void` low_move_backward(`int` `n`)`

      Method low_move_downward

        ``void` low_move_downward(`int` `n`)`

      Method low_move_forward

        ``void` low_move_forward(`int` `n`)`

      Method low_move_upward

        ``void` low_move_upward(`int` `n`)`

      Method low_write

        ``void` low_write(`string` `s`, `void`|`int` `word_break`)`

      Method move_backward

        ``void` move_backward(`string` `s`)`

      Method move_forward

        ``void` move_forward(`string` `s`)`

      Method newline

        ``void` newline()`

      Method turn_off

        ``void` turn_off(`string` ... `atts`)`

      Description

        Set the provided attributes to off.

      Method turn_on

        ``void` turn_on(`string` ... `atts`)`

      Description

        Set the provided attributes to on.

      Method write

        ``void` write(`string` `s`, `void`|`int` `word_break`, `void`|`int` `hide`)`

  ## Module Stdio

    Constant DATA_CHUNK_SIZE

      ```final` constant` `int` Stdio.`DATA_CHUNK_SIZE``

    Description

      Size used in various places to divide incoming or outgoing data into chunks.

    Constant NOTE_ATTRIB

      ``constant` `int` Stdio.`NOTE_ATTRIB``

    Constant NOTE_DELETE

      ``constant` `int` Stdio.`NOTE_DELETE``

    Constant NOTE_EXTEND

      ``constant` `int` Stdio.`NOTE_EXTEND``

    Constant NOTE_LINK

      ``constant` `int` Stdio.`NOTE_LINK``

    Constant NOTE_RENAME

      ``constant` `int` Stdio.`NOTE_RENAME``

    Constant NOTE_REVOKE

      ``constant` `int` Stdio.`NOTE_REVOKE``

    Constant NOTE_WRITE

      ``constant` `int` Stdio.`NOTE_WRITE``

    Constant PROP_BIDIRECTIONAL

      ``constant` `int` Stdio.`PROP_BIDIRECTIONAL``

    Description

      The file is bi-directional.

    See also

      `Stdio.File()->pipe()`

    Constant PROP_BUFFERED

      ``constant` `int` Stdio.`PROP_BUFFERED``

    Description

      The file is buffered (usually 4KB).

    See also

      `Stdio.File()->pipe()`

    Constant PROP_IPC

      ``constant` `int` Stdio.`PROP_IPC``

    Description

      The file may be used for inter process communication.

    See also

      `Stdio.File()->pipe()`

    Constant PROP_NONBLOCK

      ``constant` `int` Stdio.`PROP_NONBLOCK``

    Description

      The file supports nonblocking I/O.

    See also

      `Stdio.File()->pipe()`

    Constant PROP_REVERSE

      ``constant` `int` Stdio.`PROP_REVERSE``

    Description

      Request reversed operation.

      Used as argument to `Stdio.File()->pipe()`, when `PROP_BIDIRECTIONAL` hasn't been specified, to request the direction of the resulting pipe to reversed.

    See also

      `Stdio.File()->pipe()`

    Constant PROP_SEND_FD

      ``constant` `int` Stdio.`PROP_SEND_FD``

    Description

      The `Stdio.File` object might support the `Stdio.File()->send_fd()` operation.

    See also

      `Stdio.File()->pipe()`, `Stdio.File()->send_fd()`, `Stdio.File()->receive_fd()`

    Constant PROP_SHUTDOWN

      ``constant` `int` Stdio.`PROP_SHUTDOWN``

    Description

      The file supports shutting down transmission in either direction.

    See also

      `Stdio.File()->close()`, `Stdio.File()->pipe()`

    Constant PROP_TTY

      ``constant` `int` Stdio.`PROP_TTY``

    Description

      The `Stdio.File` object supports tty operations.

    Note

      This constant is only present on platforms where pseudo tty (aka pty) operations are available, and may thus be used to detect whether such operations should be attempted.

    See also

      `Stdio.File()->pipe()`

    Constant TCSADRAIN

      ``constant` `string` Stdio.`TCSADRAIN``

    Description

      Argument to `Stdio.File()->tcsetattr()`.

      Change after all output has been written.

    Constant TCSAFLUSH

      ``constant` `string` Stdio.`TCSAFLUSH``

    Description

      Argument to `Stdio.File()->tcsetattr()`.

      Change after all output has been written, and empty the input buffers.

    Constant TCSANOW

      ``constant` `string` Stdio.`TCSANOW``

    Description

      Argument to `Stdio.File()->tcsetattr()`.

      Change immediately.

    Constant XATTR_CREATE

      ``constant` Stdio.`XATTR_CREATE``

    Description

      Used by `setxattr` function and method to signify a pure create, which will fail if the attribute already exists.

    Constant XATTR_REPLACE

      ``constant` Stdio.`XATTR_REPLACE``

    Description

      Used by `setxattr` function and method to signify a replace, which will fail the the attribute does not already exists.

    Constant __HAVE_CONCURRENT_CLOSE__

      ``constant` Stdio.`__HAVE_CONCURRENT_CLOSE__``

    Description

      Support concurrent closing of files while other blocking operations (eg `Stdio.File->read()` or `Stdio.File()->write()`) are active in other threads. This is typically used to implement timeout recovery.

    Note

      Support for concurrent closing of files is present in Pike 8.0.1950, Pike 9.0.11 and later on most non-NT platforms.

    See also

      `Stdio.File()->close()`

    Constant __HAVE_OOB__

      ``constant` Stdio.`__HAVE_OOB__``

    Description

      Exists and has the value 1 if OOB operations are available.

    Note

      In Pike 7.5 and later OOB operations are always present.

    Constant __HAVE_SEND_FD__

      ``constant` Stdio.`__HAVE_SEND_FD__``

    Description

      Support for sending of file descriptors over `Stdio.File()->pipe()` objects with `PROP_SEND_FD` capability is supported.

    See also

      `Stdio.File()->send_fd()`, `Stdio.File()->receive_fd()`, `Stdio.File()->read()`, `Stdio.File()->write()`, `Stdio.File()->pipe()`

    Constant __OOB__

      ``constant` Stdio.`__OOB__``

    Description

      Implementation level of nonblocking I/O OOB support.

      ``0`` | Nonblocking OOB support is not supported.
      ``1`` | Nonblocking OOB works a little.
      ``2`` | Nonblocking OOB almost works.
      ``3`` | Nonblocking OOB works as intended.
      ``-1`` | Unknown level of nonblocking OOB support.

      This constant only exists when OOB operations are available, i.e. when `__HAVE_OOB__` is 1.

    Method append_file

      ``int` append_file(`string` `filename`, `string` `str`, `int`|`void` `access`)`

    Description

      Append the string `str` onto the file `filename`.

      For a description of `access`, see `Stdio.File->open()`.

    Throws

      Throws an error if `filename` couldn't be opened for writing.

    Returns

      Returns the number of bytes written, i.e. `sizeof(str)`.

    See also

      `write_file()`, `read_bytes()`, `Stdio.File()->open()`

    Method append_path
    Method append_path_unix
    Method append_path_nt

      ``string` append_path(`string` `absolute`, `string` ... `relative`)`
      ``string` append_path_unix(`string` `absolute`, `string` ... `relative`)`
      ``string` append_path_nt(`string` `absolute`, `string` ... `relative`)`

    Description

      Append `relative` paths to an `absolute` path and remove any `"//"`, `"../"` or `"/."` to produce a straightforward absolute path as a result.

      `"../"` is ignorded in the relative paths if it makes the created path begin with something else than the absolute path (or so far created path).

      `append_path_nt()` fixes drive letter issues in `relative` by removing the colon separator `":"` if it exists (k:/fnord appends as k/fnord)

      `append_path_nt()` also makes sure that UNC path(s) in `relative` is appended correctly by removing any `"\\"` or `"//"` from the beginning.

      `append_path()` is equivalent to `append_path_unix()` on UNIX-like operating systems, and equivalent to `append_path_nt()` on NT-like operating systems.

    See also

      `combine_path()`

    Method async_cp

      ``void` async_cp(`string` `from`, `string` `to`, `function`(`int`, `mixed` ... :`void`) `callback`, `mixed` ... `args`)`

    Description

      Copy a file asynchronously.

      This function is similar to `cp()`, but works asynchronously.

    Parameter `from`

      Name of file to copy.

    Parameter `to`

      Name of file to create or replace with a copy of `from`.

    Parameter `callback`

      Function to be called on completion. The first argument will be `1` on success, and `0` (zero) otherwise. The rest of the arguments to `callback` are passed verbatim from `args`.

    Parameter `args`

      Extra arguments to pass to `callback`.

    Note

      For `callback` to be called, the backend must be active (ie `main()` must have returned `-1`, or `Pike.DefaultBackend` get called in some other way). The actual copying may start before the backend has activated.

    Bugs

      Currently the file sizes are not compared, so the destination file (`to`) may be truncated.

    See also

      `cp()`, `sendfile()`

    Method convert_modestring2int

      ``int` convert_modestring2int(`string` `mode_string`)`

    Description

      Convert the mode_string string as returned by Stdio.Stat object to int suitable for chmod

    Parameter `mode_string`

      The string as return from Stdio.Stat()->mode_string

    Returns

      An int matching the permission of the mode_string string suitable for chmod

    Method cp

      ``int` cp(`string` `from`, `string` `to`)`

    Description

      Copies the file `from` to the new position `to`. If there is no system function for cp, a new file will be created and the old one copied manually in chunks of `DATA_CHUNK_SIZE` bytes.

      This function can also copy directories recursively.

    Returns

      0 on error, 1 on success

    Note

      This function keeps file and directory mode bits, unlike in Pike 7.6 and earlier.

    Method exist

      ``int` exist(`string` `path`)`

    Description

      Check if a `path` exists.

    Returns

      Returns true if the given path exists (is a directory or file), otherwise false.

    Note

      May fail with eg `errno()` `EFBIG` if the file exists, but the filesystem doesn't support the file size.

    See also

      `is_dir()`, `is_file()`, `is_link()`, `file_stat()`

    Method file_equal

      ``int` file_equal(`string` `file_1`, `string` `file_2`)`

    Description

      Returns nonzero if the given paths are files with identical content, returns zero otherwise. Zero is also returned for any sort of I/O error.

    Method file_size

      ``int` file_size(`string` `filename`)`

    Description

      Give the size of a file. Size -1 indicates that the file either does not exist, or that it is not readable by you. Size -2 indicates that it is a directory, -3 that it is a symlink and -4 that it is a device.

    See also

      `file_stat()`, `write_file()`, `read_bytes()`

    Method get_all_active_fd

      ``array`(`int`) get_all_active_fd()`

    Description

      Returns the id of all the active file descriptors.

    Method gethostip

      ``mapping`(`string`:`mapping`) gethostip()`

    Description

      Returns the IP addresses of the host.

    Returns

      Returns a mapping that maps interface name to a mapping with more information about that interface. That information mapping looks as follows.

      ``"ips"` : `array`(`string`)` | A list of all IP addresses bound to this interface.

    Inherit _Stdio

      `inherit _Stdio : _Stdio`

    Method is_dir

      ``int` is_dir(`string` `path`)`

    Description

      Check if a `path` is a directory.

    Returns

      Returns true if the given path is a directory, otherwise false.

    See also

      `exist()`, `is_file()`, `is_link()`, `file_stat()`

    Method is_file

      ``int` is_file(`string` `path`)`

    Description

      Check if a `path` is a file.

    Returns

      Returns true if the given path is a regular file, otherwise false.

    See also

      `exist()`, `is_dir()`, `is_link()`, `file_stat()`

    Method is_link

      ``int` is_link(`string` `path`)`

    Description

      Check if a `path` is a symbolic link.

    Returns

      Returns true if the given path is a symbolic link, otherwise false.

    See also

      `exist()`, `is_dir()`, `is_file()`, `file_stat()`

    Method mkdirhier

      ``int` mkdirhier(`string` `pathname`, `void`|`int` `mode`)`

    Description

      Creates zero or more directories to ensure that the given `pathname` is a directory.

      If a `mode` is given, it's used for the new directories after being &'ed with the current umask (on OS'es that support this).

    Returns

      Returns zero on failure and nonzero on success.

    See also

      `mkdir()`

    Method perror

      ``void` perror(`string` `s`)`

    Description

      This function prints a message to stderr along with a description of what went wrong if available. It uses the system errno to find out what went wrong, so it is only applicable to IO errors.

    See also

      `werror()`

    Method read_bytes

      ``string` read_bytes(`string` `filename`, `int` `start`, `int` `len`)`
      ``string` read_bytes(`string` `filename`, `int` `start`)`
      ``string` read_bytes(`string` `filename`)`

    Description

      Read `len` number of bytes from a regular file `filename` starting at byte `start`, and return it as a string.

      If `len` is omitted, the rest of the file will be returned.

      If `start` is also omitted, the entire file will be returned.

    Throws

      Throws an error on any I/O error except when the file doesn't exist.

    Returns

      Returns `0` (zero) if the file doesn't exist or if `start` is beyond the end of it.

      Returns a string with the requested data otherwise.

    See also

      `read_file`, `write_file()`, `append_file()`

    Typedef read_callback_t

      ```local` typedef` `function`(`mixed`|`void`, `string`:`int`|`void`)|`function`(`mixed`|`void`, `Buffer`:`int`|`void`)|`function`(`mixed`|`void`:`int`|`void`) Stdio.`read_callback_t``

    Description

      The various read_callback signatures.

      The string (or void) version is used when buffer mode (see `set_buffer_mode`) has not been enabled for reading.

      The `Buffer` version is used when a `Buffer` has been enabled for reading.

      In both cases the data is the newly arrived data, but in buffered mode data you did not fully read in the last read callback is kept in the buffer.

    Method read_file

      ``string` read_file(`string` `filename`)`
      ``string` read_file(`string` `filename`, `int` `start`, `int` `len`)`

    Description

      Read `len` lines from a regular file `filename` after skipping `start` lines and return those lines as a string. If both `start` and `len` are omitted the whole file is read.

    Throws

      Throws an error on any I/O error except when the file doesn't exist.

    Returns

      Returns `0` (zero) if the file doesn't exist or if `start` is beyond the end of it.

      Returns a string with the requested data otherwise.

    See also

      `read_bytes()`, `write_file()`

    Method recursive_mv

      ``int` recursive_mv(`string` `from`, `string` `to`)`

    Description

      Copy a file or a directory tree by copying and then removing. Mode bits are preserved in the copy. It's not the fastest but works on every OS and works well across different file systems.

    Returns

      Returns 0 on failure, nonzero otherwise.

    See also

      `recursive_rm` `cp`

    Method recursive_rm

      ``int` recursive_rm(`string` `path`)`

    Description

      Remove a file or a directory tree.

    Returns

      Returns 0 on failure, nonzero otherwise.

    See also

      `rm`

    Method sendfile

      ``object` sendfile(`array`(`string`) `headers`, `File` `from`, `int` `offset`, `int` `len`, `array`(`string`) `trailers`, `File` `to`)`
      ``object` sendfile(`array`(`string`) `headers`, `File` `from`, `int` `offset`, `int` `len`, `array`(`string`) `trailers`, `File` `to`, `function`(`int`, `mixed` ... :`void`) `callback`, `mixed` ... `args`)`

    Description

      Sends `headers` followed by `len` bytes starting at `offset` from the file `from` followed by `trailers` to the file `to`. When completed `callback` will be called with the total number of bytes sent as the first argument, followed by `args`.

      Any of `headers`, `from` and `trailers` may be left out by setting them to `0`.

      Setting `offset` to `-1` means send from the current position in `from`.

      Setting `len` to `-1` means send until `from`'s end of file is reached.

    Note

      The sending is performed asynchronously, and may complete both before and after the function returns.

      For `callback` to be called, the backend must be active (ie `main()` must have returned `-1`, or `Pike.DefaultBackend` get called in some other way).

      In some cases, the backend must also be active for any sending to be performed at all.

      In Pike 7.4.496, Pike 7.6.120 and Pike 7.7 and later the backend associated with `to` will be used rather than the default backend. Note that you usually will want `from` to have the same backend as `to`.

    Note

      The low-level sending may be performed with blocking I/O calls, and thus trigger the process being killed with `SIGPIPE` when the peer closes the other end. Add a call to `signal()` to avoid this.

    Bugs

      FIXME: Support for timeouts?

    See also

      `Stdio.File->set_nonblocking()`

    Method simplify_path

      ``string` simplify_path(`string` `path`)`

    Description

      Returns a canonic representation of `path` (without /./, /../, // and similar path segments).

    Variable stderr

      ``FILE` Stdio.stderr`

    Description

      An instance of `FILE("stderr")`, the standard error stream. Use this when you want to output error messages.

    See also

      `predef::werror()`

    Variable stdin

      ``FILE` Stdio.stdin`

    Description

      An instance of `FILE("stdin")`, the standard input stream. Use this when you want to read anything from the standard input. This example will read lines from standard input for as long as there are more lines to read. Each line will then be written to stdout together with the line number. We could use `Stdio.stdout.write()` instead of just `write()`, since they are the same function.

    Example

          int main()
            {
              int line;
              while(string s=Stdio.stdin.gets())
           	 write("%5d: %s\n", line++, s);
            }

    Variable stdout

      ``FILE` Stdio.stdout`

    Description

      An instance of `FILE("stdout")`, the standatd output stream. Use this when you want to write anything to the standard output.

    See also

      `predef::write()`

    Method werror

      ``void` werror(`string` `s`)`

    Description

      Write a message to stderr. Stderr is normally the console, even if the process output has been redirected to a file or pipe.

    Note

      This function is identical to `predef::werror()`.

    See also

      `predef::werror()`

    Typedef write_callback_t

      ```local` typedef` `function`(`mixed`|`void`:`int`|`void`)|`function`(`mixed`|`void`, `Buffer`:`int`|`void`) Stdio.`write_callback_t``

    Description

      The various write_callback signatures.

      The void version is used when buffer mode (see `set_buffer_mode`) has not been enabled for writing.

      The `Buffer` version is used when a `Buffer` has been enabled for writing, add data to that buffer to send it.

    Method write_file

      ``int` write_file(`string` `filename`, `string` `str`, `int`|`void` `access`)`

    Description

      Write the string `str` onto the file `filename`. Any existing data in the file is overwritten.

      For a description of `access`, see `Stdio.File()->open()`.

    Throws

      Throws an error if `filename` couldn't be opened for writing.

    Returns

      Returns the number of bytes written, i.e. `sizeof(str)`.

    See also

      `append_file()`, `read_bytes()`, `Stdio.File()->open()`

    ## Class Stdio.BlockFile

      Description

        The Stdio.BlockFile API.

        This class exists purely for typing reasons.

        Use in types in place of `Stdio.File` where only blocking I/O is done with the object.

      See also

        `Stream`, `NonblockingStream`, `File`, `FILE`

      Inherit Stream

        `inherit Stream : Stream`

      Method seek

        ``int` seek(`int` `to`, `string`|`void` `how`)`

      Method tell

        ``int` tell()`

    ## Class Stdio.Buffer

      Description

        A buffer to use as input or buffering when doing I/O. It is similar to `String.Buffer`, but can only contain 8bit data and is designed for protocol parsing. It is optimized for reading from the beginning and adding to the end, and will try to minimize the amount of data copying that is done.

        The class maintains two separate offsets, one for reading and one for writing. The functions that add data all do so at the write offset (the end of the buffer), and reading is done from the read offset (the start of the buffer).

        The class can also be used to directly read from and write to filedescriptors if so desired. This eliminates at least one memory copy.

      Note

        The "avoid copy" part means that a Buffer will never shrink unless you call the `trim` function.

      Method __fd_set_output

        ``int` __fd_set_output(`object`|`function`(`string`:`int`) `write_callback`)`

      Description

        This tells the buffer to trigger the write callback for the specified filedescriptor when data is added to the buffer.

        This is used internally by Stdio.File to handle nonblocking buffered mode, and is not really intended to be used directly.

        If `write_callback` is `0` (zero) the state is cleared.

      Method _encode
      Method _decode

        `string(8bit) encode_value(Stdio.Buffer data)`
        `Stdio.Buffer decode_value(string(8bit) data)`

      Description

        Encode and decode Stdio.Buffer objects. Only the buffer data is kept, no other state is saved.

      Method _search

        ``int(-1..)` search(Stdio.Buffer from, `int(8bit)` `character`, `int`|`void` `start`, `int(0..)`|`void` `end`)`

      Description

        Search forward from the indicated `start` position for the specified `character`.

      Parameter `character`

        Character to search for.

      Parameter `start`

        Start position relative to the current read position of the buffer.

        Negative `start` values are supported and indicate positions prior to the current read position.

      Parameter `end`

        Don't search past this position of the buffer.

      Returns

        Returns the first found position of `character` relative to the current read position of the buffer on success, and `UNDEFINED` on not found. The read position is not advanced.

      See also

        `read_cstring()`, `search()`, `lfun::_search()`

      Method _search

        ``int(-1..)` search(Stdio.Buffer from, `string(8bit)` `substring`, `int`|`void` `start`, `int`|`void` `end`)`

      Description

        Search forward from the indicated `start` position for the specified `substring`.

      Parameter `substring`

        Substring to search for.

      Parameter `start`

        Start position relative to the current read position of the buffer.

        Negative `start` values are supported and indicate positions prior to the current read position.

      Parameter `end`

        Don't search past this position of the buffer.

      Returns

        Returns the first found position of `substring` relative to the current read position of the buffer on success, and `UNDEFINED` on not found. The read position is not advanced.

      See also

        `read_cstring()`, `search()`, `lfun::_search()`

      Method _sizeof

        ``int` sizeof( Stdio.Buffer arg )`

      Description

        Returns the buffer size, in bytes. This is how much you can read from the buffer until it runs out of data.

      Method `[]

        ``int` res = `Stdio.Buffer()`[ `off` ]`

      Description

        Return the character at the specified offset.

      Method `[]=

        ``Stdio.Buffer()`[ `off` ] = `char``

      Description

        Set the character at the specified offset to `char`.

      Method add

        ``Buffer` add(`AddArgument` ... `data`)`

      Description

            private typedef System.Memory|Stdio.Buffer|String.Buffer BufferObject;
             private typedef BufferObject|string(8bit)|int(8bit)|array(AddArgument) AddArgument;

        Add the items in data to the end of the buffer.

        The supported argument types are:

        ``string(8bit)`` | An eight bit string.
        ``int(8bit)`` | A single byte
        ``System.Memory`` | A chunk of memory. The whole memory area is added.
        ``Stdio.Buffer`` | A chunk of memory. The whole memory area is added.
        ``String.Buffer`` | A chunk of memory. The whole memory area is added.
        ``array`(`AddArgument`)` | Add all elements in the array individually. Each element may be any one of the types listed here.

      See also

        `sprintf`, `add_int8`, `add_int16`, `add_int32`, `add_int` and `add_hstring`

      Method add_hint

        ``Buffer` add_hint(`int` `i`, `int(0..)` `size_width`)`

      Description

        First add the size of the integer when encoded to base 256 as a `size_width` integer, then add the integer to the buffer, both in network byte order.

        `size_width` must be less than Int.NATIVE_MAX.

      Method add_hstring

        ``Buffer` add_hstring(`string(8bit)` `data`, `int` `size_size`)`
        ``Buffer` add_hstring(`Stdio.Buffer` `data`, `int` `size_size`)`
        ``Buffer` add_hstring(`System.Memory` `data`, `int` `size_size`)`
        ``Buffer` add_hstring(`String.Buffer` `data`, `int` `size_size`)`
        ``Buffer` add_hstring(`int(8bit)` `data`, `int` `size_size`)`
        ``Buffer` add_hstring(`array` `data`, `int` `size_size`)`
        ``Buffer` add_hstring(`int`|`string(8bit)`|`Stdio.Buffer`|`System.Memory`|`array` `data`, `int` `size_size`, `int` `offset`)`

      Description

        Adds length of data followed by `data` to the buffer.

        This is identical to `sprintf("%"+size_size+"H",(string)Stdio.Buffer(data))` but significantly faster.

        `size_size` is the number of bytes used to represent the length of the data. It must be less than Int.NATIVE_MAX.

        `offset` is added to the length of the data prior to writing out the length. Typical usage involves adding `size_size` to account for the room used by the size.

        The supported `data` argument types are

        ``int(8bit)`` | An eight bit character.
        ``string(8bit)`` | An eight bit string.
        ``System.Memory`` | A chunk of memory. The whole memory area is added.
        ``Stdio.Buffer`` | A chunk of memory. The whole memory area is added.
        ``String.Buffer`` | A chunk of memory. The whole memory area is added.
        ``array`` | Add all elements in the array individually. Each element may be any one of the types listed here.

      Method add_int

        ``Buffer` add_int(`int` `i`, `int(0..)` `width`)`

      Description

        Adds a generic integer to the buffer as an (width*8)bit network byteorder number.

        `width` must be less than Int.NATIVE_MAX.

      Method add_int16

        ``Buffer` add_int16(`int(16bit)`)`

      Description

        Add a 16-bit network byte order value to the buffer

      Method add_int32

        ``Buffer` add_int32(`int` `i`)`

      Description

        Adds a 32 bit network byte order value to the buffer

      Method add_int8

        ``Buffer` add_int8(`int(8bit)`)`

      Description

        Adds a single byte to the buffer.

      Method add_ints

        ``Buffer` add_ints(`array`(`int`) `integers`, `int(8bit)` `len`)`

      Description

        Add the integers in the specified array, `len` bytes per int. Equivalent to calling `add_int` for each integer, but faster, and if an error occurs the buffer will contain no new data. Either all or none of the integers will be added.

        Errors can occur if one of the elements in `integers` is not actually an integer, if sizeof(integers)*len is bigger than can be represented in a size_t, or if the buffer cannot grow due to an out of memory condition.

      Method add_padding

        ``Buffer` add_padding(`int(0..)` `nbytes`, `int(8bit)`|`void` `byte`)`

      Description

        Add `nbytes` bytes of padding, if `byte` is not specified the area will be filled with 0's, otherwise the specified byte will be repeated.

      Method cast

        `(`string`)Stdio.Buffer()`

      Description

        Convert the buffer to a string.

      Note

        This only works for buffers whose length is less than 0x7fffffff.

      Method clear

        ``void` clear()`

      Description

        Clear the buffer.

      Method consume

        ``int(0..)`|`int(-1..-1)` consume(`int(0..)` `n`)`

      Description

        Discard the first `n` bytes from the buffer

        Returns -1 on error and the amount of space still left otherwise.

      Method create

        `Stdio.Buffer Stdio.Buffer(`int`|`void` `len`)`
        `Stdio.Buffer Stdio.Buffer(`string(8bit)` `contents`)`
        `Stdio.Buffer Stdio.Buffer(`System.Memory`|`String.Buffer` `contents`)`

      Description

        If passed an integer or no argument, create a buffer of that size, or if no argument is given, 226 bytes.

        If `contents` are specified a new buffer with the contents of the given string/System.Memory or String.Buffer will be created.

      Note

        In the `String.Buffer` case the data has to be copied unless there is only one reference to the String.Buffer object, since modifications of the String.Buffer would cause the Buffer to point into invalid memory.

        In all other cases this will not copy the string data, instead data will be read from the source until it needs to be modified, so the buffer creation is fast regardless of the length of the string.

        However, as an example, if the buffer is created with a 100Gb `System.Memory` mmap:ed file as the `contents` and you later on try to modify the buffer using one of the `add` functions (or `sprintf` and similar) the old contents will be copied.

        You can use `read_only()` to avoid accidents.

      Method input_from

        ``int(-1..)` input_from(`Stdio.Stream` `f`, `int`|`void` `nbytes`)`

      Description

        Read data from `f` into this buffer. If `nbytes` is not specified, read until there is no more data to read (currently).

        Returns the amount of data that was read, or `-1` on read error.

      Note

        Please note that this funcition will read all data from the filedescriptor unless it's set to be non-blocking.

      Method lock

        ``object` lock()`

      Description

        Makes this buffer read only until the returned object is released.

      Note

        This currently simply returns a 0-length subbuffer.

      Method match

        ``mixed` match(`string(8bit)` `format`)`

      Description

        Reads data from the beginning of the buffer to match the specifed format, then return the match.

        The non-matching data will be left in the buffer.

        This function is very similar to `sscanf`, but the result is the sum of the matches. Most useful to match a single value.

      Example

            // get the next whitespace separated word from the buffer.
             buffer->match("%*[ \t\r\n]%[^ \t\r\n]");

      Method output_to

        ``int(-1..)` output_to(`Stdio.Stream`|`function`(`string`:`int`) `fun`, `int(0..)`|`void` `nbytes`)`

      Description

        Write data from the buffer to the indicated file.

      Parameter `fun`

        Write function. Either one of:

        ``Stdio.Stream`` | A file object in which the function `write()` will be called.
        ``function`(`string`:`int`)` | A function which will be called with a `string(8bit)` to write and is expected to return an `int` indicating the number of bytes successfully written or `-1` on failure.

      Parameter `nbytes`

        If `nbytes` is not specified the whole buffer will be written if possible. Otherwise at most `nbytes` will be written.

      Returns

        Will return the number of bytes that have been written successfully.

        If no bytes have been written successfully and `fun()` failed with an error, `-1` will be returned.

      Method range_error

        ``protected` `bool` range_error(`int` `howmuch`)`

      Description

        This function is called when an attempt is made to read out of bounds.

        The default implementation simply returns `0` (zero).

        Override this function to change the behavior.

      Parameter `howmuch`

        The argument `howmuch` indicates how much data is needed:

        ``(1..)`` | Need `howmuch` bytes more
        ``0`` | The amount of data needed is not certain. This most often happens when `sscanf` or `read_json` is used
        ``(..-1)`` | Tried to `unread` -`howmuch` bytes. There is usually no way to satisfy the requested range. The only supported way is to extract the data from the buffer, add the requested amount of "go backbuffer", add the data back, and forward -`howmuch` bytes.

      Returns

        `true` if the operation should be retried, `false` otherwise.

        Do not return true unless you have added data to the buffer, doing so could result in an infinite loop (since no data is added, the range_error will be called again immediately).

      Method read

        ``string(8bit)` read(`int` `n`)`

      Description

        Read `n` bytes of data from the buffer.

        If there is not enough data available this returns 0.

      See also

        `try_read()`

      Method read

        ``string(8bit)` read()`

      Description

        Read all data from the buffer.

        If there is not enough data available this returns 0.

        This is basically equivalent to (string)buffer, but it also removes the data from the buffer.

      See also

        `try_read()`

      Method read_buffer

        ``Buffer` read_buffer(`int` `n`)`
        ``Buffer` read_buffer(`int` `n`, `bool` `copy`)`

      Description

        Same as `read`, but returns the result as an Buffer.

        No data is copied unless `copy` is specified and true, the new buffer points into the old one.

      Note

        As long as the subbuffer exists no data can be added to the main buffer.

        Usually this is OK, since it often represents something that should be parsed before the next whatever is extracted from the buffer, but do take care.

      Method read_cstring

        ``string(8bit)` read_cstring()`

      Description

        Reads a \0 terminated C-string and returns the string excluding the terminating \0.

        If there is not enough data available return UNDEFINED.

        Note that pike string can not be longer than 0x7fffffff bytes (~2Gb).

      See also

        `_search()`

      Method read_hbuffer

        ``Buffer` read_hbuffer(`int` `n`)`
        ``Buffer` read_hbuffer(`int` `n`, `bool` `copy`)`

      Description

        Same as `read_hstring`, but returns the result as an Buffer.

        No data is copied unless `copy` is specified and true, the new buffer points into the old one.

      Note

        As long as the subbuffer exists no data can be added to the main buffer.

        Usually this is OK, since it often represents something that should be parsed before the next whatever is extracted from the buffer, but do take care.

        If you need to unlink the new buffer after it has been created, call `trim` in it.

      Method read_hint

        ``int` read_hint(`int` `n`)`

      Description

        Read a network byte order unsigned number of size n*8 bits, then read another network byte order number of the size indicated by the first size.

        Will return -1 if there is not enough buffer space available unless error mode is set to throw errors.

      Method read_hstring

        ``string(8bit)` read_hstring(`int(0..)` `n`, `void`|`int` `offset`)`

      Description

        Identical in functionality to `read`(`read_number`(`n`)) but faster.

        Read a network byte order number of size n*8 bits, then return the indicated number of bytes as a string.

        `offset` is substracted from the specified length prior to reading the string. Typical usage involves substracting `n` to account for the room used by the size.

        If there is not enough data available return 0.

        Note that pike string can not be longer than 0x7fffffff bytes (~2Gb).

      Method read_int

        ``int` read_int(`int` `n`)`

      Description

        Read a network byte order unsigned number of size n*8 bits, then return it.

        Will return -1 if there is not enough buffer space available unless error mode is set to throw errors.

      Method read_int16

        ``int(16bit)` read_int16()`

      Method read_int24

        ``int(24bit)` read_int24()`

      Method read_int32

        ``int(32bit)` read_int32()`

      Method read_int8

        ``int(8bit)` read_int8()`

      Method read_ints

        ``array`(`int`) read_ints(`int` `n`, `int` `width`)`

      Description

        Read a list of `n` network byte order unsigned numbers each of size `width`*8 bits, then return it.

        Will return 0 if there is not enough buffer space available unless error mode is set to throw errors.

      Method read_json

        ``mixed` read_json(`int`|`void` `require_whitespace_separator`)`

      Description

        Read a single JSON expression from the buffer and return it.

        If `require_whitespace_separator` is true there must be a whitespace after each json value (as an example, newline or space).

        The JSON is assumed to be utf-8 encoded.

      Returns

        UNDEFINED if no data is available to read. The read value otherwise.

      Note

        Unless whitespaces are required this function only really work correctly with objects, arrays and strings.

        There is really no way to see where one value starts and the other ends for most other cases

      Method read_only

        ``void` read_only()`

      Description

        Make the buffer permanently read only.

      Note

        You can use lock() to do this temporarily.

      Method read_sint

        ``int` read_sint(`int` `size`)`

      Description

        Read a network byte order two:s complement signed number of size n*8 bits, then return it.

        Will return UNDEFINED if there is not enough buffer space available unless error mode is set to throw errors.

      Method rewind_on_error
      Method rewind_key

        ``RewindKey` rewind_on_error()`
        ``RewindKey` rewind_key()`

      Description

        These functions are very similar. The `rewind_on_error` edition will create an object that, when it goes out of scope without having been destructed explicitly, will cause the buffer to rewind to the location it had when this function is called.

        This will happen if you throw an error or otherwise let the object fall out of scope.

        Use `destruct(RewindKey)` or `RewindKey.release` to stop the buffer from being rewound.

        The second version (`rewind_key`) requires you to explicitly call `RewindKey.rewind` to do the rewind.

        Take some care with these objects, if you create multiple ones at once the results might be somewhat confusing if you do not release them in the reverse order they were created in (then again, you almost certainly really only need one)

        You can call `RewindKey.update` in the generated object to change where it will be rewound to.

        The typical use-case of this functionality is when parsing a packet protocol with variable length packets where the length is not immediately known. It saves you from keeping track of how much to rewind if you had not actually gotten the whole packet yet.

      Example

            void parse_packet( Stdio.Buffer b )
            {
              Stdio.Buffer.RewindKey rewind = b->rewind_on_error();
              b->set_error_mode(1);

              switch( b->read_int8() ) // packet type
              {
                case DATA:
                  int channel = b->read_int8();
                  Stdio.Buffer data = b->read_hbuffer( 4 );
                  // we have read the whole packet, so no longer rewind on error.
                  rewind->release();
                  return handle_data_packet( channel, data );
              }
            }

      Note

        Just calling `rewind_on_error` without assigning the return value to something will not do anything. You need to keep the object around while the rewind-to position is still valid.

        Keeping the object around forbids the buffer from moving data inside itself, this means that it can only grow. So do not keep the rewind key when it is not needed.

      Method set_error_mode

        ``Buffer` set_error_mode(`int` `m`)`
        ``Buffer` set_error_mode(`program` `m`)`

      Description

        Set the error mode of this buffer to `m`.

        If true operations that would normally return 0 (like trying to read too much) will instead throw an error. If `m` is a program a clone of it will be thrown on error.

        This is useful when parsing received data, you do not have to verify that each and every read operation suceeds.

        However, the non-error mode is more useful when checking to see if a packet/segment/whatever has arrived.

        The thrown error object will have the constant buffer_error set to a non-false value.

      Example

            void read_callback(int i, string new_data)
            {
              inbuffer->add( new_data );

              while( Buffer packet = inbuffer->read_hbuffer(2) )
              {
                packet->set_error_mode(Buffer.THROW_ERROR);
                if( mixed e = catch( handle_packet( packet ) ) )
                  if( e->buffer_error )
                    protocol_error(); // illegal data in packet
                  else
                    throw(e); // the other code did something bad
               }
            }

            void handle_packet( Buffer pack )
            {
              switch( pack->read_int8() )
              {
                ...
              case HEADER_FRAME:
                int num_headers = pack->read_int32();
                for( int i = 0; i<num_headers; i++ )
                 headers[pack->read_hstring(2)] = pack->read_hstring(2);
                ...
              }
            }

      Method set_max_waste

        ``void` set_max_waste(`float` `factor`)`

      Description

        Configure how much free space should be allowed, at most, as a factor of the current buffer size.

        The default is 0.5, leaving at most half the buffer as waste.

      Method sprintf

        ``Buffer` sprintf(`strict_sprintf_format` `format`, `sprintf_args` ... `args`)`

      Description

        Appends the output from `sprintf` at the end of the buffer.

        This is somewhat faster than add(sprintf(...)) since no intermediate string is created.

      Method sscanf

        ``array` sscanf(`string(8bit)` `format`)`

      Description

        Reads data from the beginning of the buffer to match the specifed format, then return an array with the matches.

        The non-matching data will be left in the buffer.

        See `array_sscanf` for more information.

      Method trim

        ``void` trim()`

      Description

        Frees unused memory.

        Note that calling this function excessively will slow things down, since the data often has to be copied.

      Note

        This function could possibly throw an out-of-memory error if the realloc fails to find a new (smaller) memory area.

      Method truncate

        ``int(0..)`|`int(-1..-1)` truncate(`int(0..)` `n`)`

      Description

        Truncates the buffer to a length of `n` bytes.

        Returns -1 on error and the number of bytes removed otherwise.

      Method try_output

        ``int(-1..)` try_output()`

      Description

        Try to write some data from the buffer to the file registered with `__fd_set_output()`.

        This is typically called from backend callbacks when it seems that it is possible to write some data to the file.

      Returns

        Returns `-1` on write error, and otherwise the number of bytes written to the file.

      See also

        `__fd_set_output()`

      Method try_read

        ``string(8bit)` try_read(`int` `len`)`

      Description

        Attempt to read some data from the buffer.

      Parameter `len`

        Read at most `len` bytes from the buffer.

      Returns

        If the buffer contains less than `len` bytes of data, the entire buffer contents are returned. Otherwise the first `len` bytes are returned.

      See also

        `read()`

      Method unread

        ``int(0..)`|`int(-1..-1)` unread(`int(0..)` `n`)`

      Description

        Rewind the buffer `n` bytes.

      Returns

        This function returns how many more bytes of buffer is available to rewind, or -1 on error.

      Note

        Unless you add new data to the buffer using any of the add functions you can always rewind.

        You can call `unread(0)` to see how much.

      ## Class Stdio.Buffer.RewindKey

        Description

          The return value of `Buffer.rewind_on_error()` and `Buffer.rewind_key()`

          This object will cause the buffer to unwind to the position it was at when the object was created either when it is released (when it falls out of scope, explicit destruct does not count) or when `rewind` is called, depending on which function was used to create it.

        Method release

          ``void` release()`

        Description

          Do not rewind if the object is released.

        Note

          This is equivalent to calling destruct() on the object

        Method rewind

          ``void` rewind()`

        Description

          Rewinds the buffer explicitly.

        Note

          Destructs this `RewindKey`

        Method update

          ``void` update()`

        Description

          Update the location the buffer will be rewound to to the current position of the buffer.

    ## Class Stdio.FakeFile

      Description

        A string wrapper that pretends to be a `Stdio.File` object in addition to some features of a `Stdio.FILE` object.

      Method _sizeof

        ``int(0..)` sizeof( Stdio.FakeFile arg )`

      Description

        Sizeof on a FakeFile returns the size of its contents.

      Method cast

        `(int)Stdio.FakeFile()
        (float)Stdio.FakeFile()
        (string)Stdio.FakeFile()
        (array)Stdio.FakeFile()
        (mapping)Stdio.FakeFile()
        (multiset)Stdio.FakeFile()`

      Description

        A FakeFile can be casted to a string.

      Method close

        ``int` close(`void`|`string` `direction`)`

      See also

        `Stdio.File()->close()`

      Method create

        `Stdio.FakeFile Stdio.FakeFile(`string` `data`, `void`|`string` `type`, `void`|`int` `pointer`)`

      See also

        `Stdio.File()->create()`

      Method dup

        ``this_program` dup()`

      See also

        `Stdio.File()->dup()`

      Method errno

        ``int` errno()`

      Description

        Always returns 0.

      See also

        `Stdio.File()->errno()`

      Method getchar

        ``int` getchar()`

      See also

        `Stdio.FILE()->getchar()`

      Method gets

        ``string` gets()`

      See also

        `Stdio.FILE()->gets()`

      Constant is_fake_file

        ``constant` `int` Stdio.FakeFile.`is_fake_file``

      Description

        This constant can be used to distinguish a FakeFile object from a real `Stdio.File` object.

      Method line_iterator

        ``String.SplitIterator` line_iterator(`int`|`void` `trim`)`

      See also

        `Stdio.File()->line_iterator()`

      Method peek

        ``int(-1..1)` peek(`int`|`float`|`void` `timeout`)`

      See also

        `Stdio.File()->peek()`

      Method query_address

        ``string` query_address(`void`|`bool` `is_local`)`

      Description

        Always returns 0.

      See also

        `Stdio.File()->query_address()`

      Method query_close_callback

        ``function`(:`void`) query_close_callback()`

      See also

        `Stdio.File()->query_close_callback`

      Method query_id

        ``mixed` query_id()`

      See also

        `Stdio.File()->query_id()`

      Method query_read_callback

        ``function`(:`void`) query_read_callback()`

      See also

        `Stdio.File()->query_read_callback`

      Method query_read_oob_callback

        ``function`(:`void`) query_read_oob_callback()`

      See also

        `Stdio.File()->query_read_oob_callback`

      Method query_write_callback

        ``function`(:`void`) query_write_callback()`

      See also

        `Stdio.File()->query_write_callback`

      Method query_write_oob_callback

        ``function`(:`void`) query_write_oob_callback()`

      See also

        `Stdio.File()->query_write_oob_callback`

      Method read

        ``string` read(`void`|`int(0..)` `len`, `void`|`bool` `not_all`)`

      See also

        `Stdio.File()->read()`

      Method read_function

        ``function`(:`string`) read_function(`int` `nbytes`)`

      See also

        `Stdio.File()->read_function()`

      Method seek

        ``int` seek(`int` `pos`, `string`|`void` `how`)`

      See also

        `Stdio.File()->seek()`

      Method set_blocking

        ``void` set_blocking()`

      See also

        `Stdio.File()->set_blocking`

      Method set_blocking_keep_callbacks

        ``void` set_blocking_keep_callbacks()`

      See also

        `Stdio.File()->set_blocking_keep_callbacks`

      Method set_close_callback

        ``void` set_close_callback(`function`(:`void`) `cb`)`

      See also

        `Stdio.File()->set_close_callback`

      Method set_id

        ``void` set_id(`mixed` `_id`)`

      See also

        `Stdio.File()->set_id()`

      Method set_nonblocking

        ``void` set_nonblocking(`function`(:`void`) `rcb`, `function`(:`void`) `wcb`, `function`(:`void`) `ccb`, `function`(:`void`) `rocb`, `function`(:`void`) `wocb`)`

      See also

        `Stdio.File()->set_blocking`

      Method set_nonblocking_keep_callbacks

        ``void` set_nonblocking_keep_callbacks()`

      See also

        `Stdio.File()->set_blocking_keep_callbacks`

      Method set_read_callback

        ``void` set_read_callback(`function`(:`void`) `cb`)`

      See also

        `Stdio.File()->set_read_callback`

      Method set_read_oob_callback

        ``void` set_read_oob_callback(`function`(:`void`) `cb`)`

      See also

        `Stdio.File()->set_read_oob_callback`

      Method set_write_callback

        ``void` set_write_callback(`function`(:`void`) `cb`)`

      See also

        `Stdio.File()->set_write_callback`

      Method set_write_oob_callback

        ``void` set_write_oob_callback(`function`(:`void`) `cb`)`

      See also

        `Stdio.File()->set_write_oob_callback`

      Method stat

        ``Stdio.Stat` stat()`

      Description

        Returns size and the creation time of the string.

      Method sync

        ``int(1..1)` sync()`

      Description

        Always returns 1.

      See also

        `Stdio.File()->sync()`

      Method tell

        ``int` tell()`

      See also

        `Stdio.File()->tell()`

      Method truncate

        ``bool` truncate(`int` `length`)`

      See also

        `Stdio.File()->truncate()`

      Method unread

        ``void` unread(`string` `s`)`

      See also

        `Stdio.FILE()->unread()`

      Method write

        ``int(-1..)` write(`string`|`array`(`string`) `str`, `mixed` ... `extra`)`

      See also

        `Stdio.File()->write()`

    ## Class Stdio.Fd

      Description

        Low level I/O operations.

      Note

        This is not the class you want. Use `Stdio.File` and friends instead.

      See also

        `Stdio.File`, `Stdio.FILE`, `_Stdio.Fd_ref`

      Variable _errno

        ``protected` `int(0..)` Stdio.Fd._errno`

      Description

        Variable containing the internal value returned by `errno()`.

      See also

        `errno()`

      Variable _fd

        ``Fd` Stdio.Fd._fd`

      Note

        Read only

      Variable _read_callback
      Variable _write_callback
      Variable _read_oob_callback
      Variable _write_oob_callback
      Variable _fs_event_callback

        ``mixed` Stdio.Fd._read_callback`
        ``mixed` Stdio.Fd._write_callback`
        ``mixed` Stdio.Fd._read_oob_callback`
        ``mixed` Stdio.Fd._write_oob_callback`
        ``mixed` Stdio.Fd._fs_event_callback`

      Description

        Callback functions installed by `Stdio.File()->set_callbacks()` et al.

      Method `<<

        ``Stdio.File` res = `Stdio.Fd()` << `data``
        ``Stdio.File` res = `Stdio.Fd()` << `data``

      Description

        Write some data to a file.

        If `data` is not a string, it is casted to string, and then written to the file.

      Note

        Throws an error if not all data could be written.

      See also

        `write()`

      Method close

        ``int` close()`
        ``int` close(`string` `direction`)`

      Description

        Close a file or stream.

        If direction is not specified, both the read and the write direction is closed. Otherwise only the directions specified is closed.

      Returns

        Nonzero is returned if the file or stream wasn't open in the specified direction, zero otherwise.

      Throws

        An exception is thrown if an I/O error occurs.

        The default behaviour for sockets is typically to flush buffered data in the background, but this can be changed with `linger()`.

      Note

        `close()` has no effect if this file object has been associated with an already opened file, i.e. if `open()` was given an integer as the first argument.

      See also

        `linger()`, `open()`, `open_socket()`

      Method connect

        ``bool` connect(`string` `dest_addr`, `int` `dest_port`)`
        ``bool` connect(`string` `dest_addr`, `int` `dest_port`, `string` `src_addr`, `int` `src_port`)`
        ``string(8bit)`|`int(0..0)` connect(`string` `dest_addr`, `int` `dest_port`, `string`|`int(0..0)` `src_addr`, `int`|`int(0..0)` `src_port`, `string(8bit)` `data`)`

      Description

        Open a TCP/IP connection to the specified destination.

        In nonblocking mode, success is indicated with the write-callback, and failure with the close-callback or the read_oob-callback.

        If the `data` argument is included the socket will use TCP_FAST_OPEN if available, if not the data will not be sent. In the data case the function either returns the data that has not been sent (only one packet can be sent with this option) or 0 if the connection failed immediately.

      Returns

        Returns `1` or the remaining `data` on success, and `0` on failure.

      Note

        In nonblocking mode `0` (zero) may be returned and `errno()` set to `EWOULDBLOCK` or `WSAEWOULDBLOCK`. This should not be regarded as a connection failure.

      Method connect_unix

        ``bool` connect_unix(`string` `filename`)`

      Description

        Open a UNIX domain socket connection to the specified destination.

      Parameter `filename`

        Filename to create.

        In nonblocking mode, success is indicated with the write-callback, and failure with the close-callback or the read_oob-callback.

      Returns

        Returns `1` on success, and `0` on failure.

      Note

        In nonblocking mode `0` (zero) may be returned and `errno()` set to `EWOULDBLOCK` or `WSAEWOULDBLOCK`. This should not be regarded as a connection failure.

      Note

        `path` had a quite restrictive length limit (~100 characters) prior to Pike 7.8.334.

      Method create

        `Stdio.Fd Stdio.Fd(`string` `filename`)`
        `Stdio.Fd Stdio.Fd(`string` `filename`, `string` `mode`)`
        `Stdio.Fd Stdio.Fd(`string` `filename`, `string` `mode`, `int` `access`)`
        `Stdio.Fd Stdio.Fd(`int` `fd`)`
        `Stdio.Fd Stdio.Fd(`int` `fd`, `string` `mode`)`

      Description

        See `open()`.

      See also

        `open()`

      Method dup

        ``Stdio.Fd` dup()`

      Description

        Duplicate the file.

      See also

        `dup2()`

      Method dup2

        ``int` dup2(`Stdio.File` `to`)`

      Description

        Duplicate a file over another.

        This function works similarly to `assign()`, but instead of making the argument a reference to the same file, it creates a new file with the same properties and places it in the argument.

      Returns

        Returns `1` on success and `0` (zero) on failure.

      Note

        In Pike 7.7 and later `to` need not be open, in which case a new fd is allocated.

      Note

        Note also that `to` is also assigned to the same backend (if any) as this object.

      See also

        `assign()`, `dup()`

      Method errno

        ``int` errno()`

      Description

        Return the errno for the latest failed file operation.

      Method fd_factory

        ``Fd` fd_factory()`

      Description

        Factory creating `Stdio.Fd` objects.

        This function is called by `openat()`, `pipe()`, `dup()` and other functions creating new file objects.

        The default implementation calls `object_program(this_object())()` to create the new object, and returns the `Fd` inherit in it.

      Note

        Note that this function must return the `Fd` inherit in the object.

      See also

        `Stdio.Port()->fd_factory()`, `openat()`, `pipe()`

      Method get_dir

        ``array`(`string`) get_dir(`string`|`void` `path`)`

      Description

        Get directory contents relative to an open directory.

      Parameter `path`

        Path relative to the open directory. Defaults to the directory itself.

      Returns

        Returns an array of filenames.

      Note

        Not available on all architectures, or in Pike 7.6 and earlier.

      See also

        `predef::get_dir()`, `statat()`, `openat()`, `unlinkat()`

      Method getxattr

        ``string` getxattr(`string` `attr`)`

      Description

        Return the value of a specified attribute, or 0 if it does not exist

      Method grantpt

        ``string` grantpt()`

      Description

        If this file has been created by calling `openpt()`, return the filename of the associated pts-file. This function should only be called once.

      Returns

        Returns the filename of the corresponding pts.

      Note

        This function is only available on some platforms.

      Method is_open

        ``int` is_open()`

      Description

        Returns true if the file is open.

      Note

        If the file is a socket that has been closed from the remote side, this function might still return true.

      Note

        Most methods can't be called for a file descriptor that isn't open. Notable exceptions `errno`, `mode`, and the set and query functions for callbacks and backend.

      Method isatty

        ``bool` isatty()`

      Description

        Returns true if the file is a terminal.

      Method linger

        ``bool` linger(`int(-1..65535)`|`void` `seconds`)`

      Description

        Set the socket linger behaviour on `close()`.

      Parameter `seconds`

        ``-1`` | Reset to default behaviour. This typically means that `close()` will return immediately, but any buffered data will still be sent if possible.
        ``0`` | Terminate the connection immediately on `close()`, and discard any buffered data.
        ``(1..65535)`` | Have `close()` wait for at most `seconds` seconds for any buffered data to be sent after which the connection is terminated.

      Returns

        Returns `1` on success, and `0` (zero) on failure.

      Note

        This operation is only valid on sockets.

      Note

        This function was not available in Pike 7.8.775 and earlier.

      See also

        `close()`

      Method listxattr

        ``array`(`string`) listxattr()`

      Description

        Return an array of all extended attributes set on the file

      Method lock

        ``Stdio.FileLockKey` lock()`
        ``Stdio.FileLockKey` lock(`bool` `is_recursive`)`

      Description

        Makes an exclusive file lock on this file.

      See also

        `trylock()`

      Method mode

        ``int` mode()`

      Description

        Returns the open mode and capabilities for the file.

      Returns

        Returns an ``|()` of the following flags:

        ``0x1000`` | `FILE_READ`
        ``0x2000`` | `FILE_WRITE`
        ``0x4000`` | `FILE_APPEND`
        ``0x8000`` | `FILE_CREATE`
        ``0x0100`` | `FILE_TRUNC`
        ``0x0200`` | `FILE_EXCLUSIVE`
        ``0x0400`` | `FILE_NONBLOCKING`
        ``0x0080`` | `PROP_TTY`
        ``0x0040`` | `PROP_SEND_FD`
        ``0x0010`` | `PROP_BIDIRECTIONAL`
        ``0x0008`` | `PROP_BUFFERED`
        ``0x0004`` | `PROP_SHUTDOWN`
        ``0x0002`` | `PROP_NONBLOCK`
        ``0x0001`` | `PROP_IPC`

      Note

        In some versions of Pike 7.7 and 7.8 the `PROP_` flags were filtered from the result.

      See also

        `open()`

      Method open

        ``int` open(`string` `filename`, `string` `mode`)`
        ``int` open(`string` `filename`, `string` `mode`, `int` `access`)`
        ``int` open(`int` `fd`, `string` `mode`)`

      Description

        Open a file, or use an existing fd.

        If `filename` is given, attempt to open the named file. If `fd` is given instead, it should be the file descriptor for an already opened file, which will then be used by this object.

        `mode` describes how the file is opened. It's a case-insensitive string consisting of one or more of the following letters:

        "r"

          Open for reading.

        "w"

          Open for writing.

        "a"

          Append new data to the end.

        "c"

          Create the file if it doesn't exist already.

        "t"

          Truncate the file to zero length if it already contains data. Use only together with `"w"`.

        "x"

          Open exclusively - the open fails if the file already exists. Use only together with `"c"`. Note that it's not safe to assume that this is atomic on some systems.

        `access` specifies the permissions to use if a new file is created. It is a UNIX style permission bitfield:

        0400

          User has read permission.

        0200

          User has write permission.

        0100

          User has execute permission.

        0040

          Group has read permission.

        0020

          Group has write permission.

        0010

          Group has execute permission.

        0004

          Others have read permission.

        0002

          Others have write permission.

        0001

          Others have execute permission.

        It's system dependent on which of these bits that are actually heeded. If `access` is not specified, it defaults to `00666`, but note that on UNIX systems it's masked with the process umask before use.

      Returns

        Returns nonzero on success and `0` (zero) on failure. If there is a failure then `errno` returns the error code.

      See also

        `close()`

      Method open_socket

        ``bool` open_socket(`int`|`void` `port`, `string`|`void` `addr`, `int`|`string`|`void` `family_hint`)`

      Method openat

        ``Stdio.File` openat(`string` `filename`)`
        ``Stdio.File` openat(`string` `filename`, `string` `mode`)`
        ``Stdio.File` openat(`string` `filename`, `string` `mode`, `int` `access`)`

      Description

        Open a file relative to an opened directory.

      Returns

        Returns a new file object on success, and `0` (zero) on failure.

      Note

        Not available on all architectures, or in Pike 7.6 and earlier.

      See also

        `open()`, `statat()`, `unlinkat()`

      Method openpt

        ``int` openpt(`string` `mode`)`

      Description

        Open the master end of a pseudo-terminal pair.

      Returns

        This function returns `1` for success, `0` otherwise.

      See also

        `grantpt()`

      Method peek

        ``int(-1..1)` peek()`
        ``int(-1..1)` peek(`int`|`float` `timeout`)`
        ``int(-1..1)` peek(`int`|`float` `timeout`, `int` `not_eof`)`

      Description

        Check if there is data available to read, or wait some time for available data to read.

        More specifically, a later call to `read()` will return immediately, either due to data being present, or due to some error (eg if a socket has been closed).

      Parameter `timeout`

        Timeout in seconds.

      Parameter `not_eof`

        Flag for specifying handling of end of file. The following values are currently defined:

        ``0`` | Traditional (and default) behaviour. Return `1` at EOF.
        ``1`` | Regard EOF as an error. Return `-1` and set `errno()` to return `EPIPE` at EOF.

      Returns

        ``1`` | There is data available to `read()`, or `not_eof` is `0` (zero) and we're at EOF. A later call to `read()` will not block.
        ``0`` | There is no data available (ie timeout).
        ``-1`` | Error condition. The error code returned by `errno()` has been updated.

      See also

        `errno()`, `read()`

      Note

        The function may be interrupted prematurely of the timeout (due to signals); check the timing manually if this is imporant.

      Note

        The `not_eof` parameter was added in Pike 7.7.

      Note

        This function was not available on NT in Pike 7.6 and earlier.

      Method pipe

        ``Stdio.File` pipe()`
        ``Stdio.File` pipe(`int` `flags`)`

      Method proxy

        ``void` proxy(`Stdio.File` `from`)`

      Description

        Starts a thread that asynchronously copies data from `from` to this file.

      See also

        `Stdio.sendfile()`

      Method query_address

        ``string` query_address()`
        ``string` query_address(`bool` `local`)`

      Description

        Get address and port of a socket end-point.

      Parameter `local`

        If the argument `local` is not specified, or is `0` (zero), the remote end-point is returned. Otherwise, if `local` is `1`, the local end-point is returned.

      Returns

        This function returns the address and port of a socket end-point on the form `"x.x.x.x port"` (IPv4) or `"x:x:x:x:x:x:x:x port"` (IPv6). IPv6 addresses may use the contracted syntax.

        If this file is not a socket, is not connected, or some other error occurs, `0` (zero) is returned and `errno()` will return the error code.

      Throws

        An error is thrown if the socket (or file) isn't open.

      See also

        `connect()`

      Method query_backend

        ``Pike.Backend` query_backend()`

      Description

        Return the backend used for the callbacks.

      See also

        `set_backend`

      Method query_fd

        ``int` query_fd()`

      Description

        Returns the file descriptor number associated with this object.

      Method read

        ``string` read()`
        ``string` read(`int` `len`)`
        ``string` read(`int` `len`, `bool` `not_all`)`

      Description

        Read data from a file or a stream.

        Attempts to read `len` bytes from the file, and return it as a string. Less than `len` bytes can be returned if:

        - end-of-file is encountered for a normal file, or

        - it's a stream that has been closed from the other end, or

        - it's a stream in nonblocking mode, or

        - it's a stream and `not_all` is set, or

        - `not_all` isn't set and an error occurred (see below).

        If `not_all` is nonzero, `read()` does not try its best to read as many bytes as you have asked for, but merely returns as much as the system read function returns. This is mainly useful with stream devices which can return exactly one row or packet at a time. If `not_all` is used in blocking mode, `read()` only blocks if there's no data at all available.

        If something goes wrong and `not_all` is set, zero is returned. If something goes wrong and `not_all` is zero or left out, then either zero or a string shorter than `len` is returned. If the problem persists then a later call to `read()` fails and returns zero, however.

        If everything went fine, a call to `errno()` directly afterwards returns zero. That includes an end due to end-of-file or remote close.

        If no arguments are given, `read()` reads to the end of the file or stream.

        If any file descriptors have been sent by the other side of the stream, `receive_fd()` will be called once for every sent file descriptor.

      Note

        It's not necessary to set `not_all` to avoid blocking reading when nonblocking mode is used.

      Note

        When at the end of a file or stream, repeated calls to `read()` will return the empty string since it's not considered an error. The empty string is never returned in other cases, unless nonblocking mode is used or `len` is zero.

      See also

        `read_oob()`, `write()`, `receive_fd()`, `send_fd()`

      Method read_oob

        ``string` read_oob()`
        ``string` read_oob(`int` `len`)`
        ``string` read_oob(`int` `len`, `bool` `not_all`)`

      Description

        Attempts to read `len` bytes of out-of-band data from the stream, and returns it as a string. Less than `len` bytes can be returned if:

        - the stream has been closed from the other end, or

        - nonblocking mode is used, or

        - `not_all` is set, or

        - `not_all` isn't set and an error occurred (see below).

        If `not_all` is nonzero, `read_oob()` only returns as many bytes of out-of-band data as are currently available.

        If something goes wrong and `not_all` is set, zero is returned. If something goes wrong and `not_all` is zero or left out, then either zero or a string shorter than `len` is returned. If the problem persists then a later call to `read_oob()` fails and returns zero, however.

        If everything went fine, a call to `errno()` directly afterwards returns zero. That includes an end due to remote close.

        If no arguments are given, `read_oob()` reads to the end of the stream.

      Note

        Out-of-band data was not supported in Pike 0.5 and earlier, and not in Pike 0.6 through 7.4 if they were compiled with the option `'--without-oob'`.

      Note

        It is not guaranteed that all out-of-band data sent from the other end is received. Most streams only allow for a single byte of out-of-band data at a time.

      Note

        It's not necessary to set `not_all` to avoid blocking reading when nonblocking mode is used.

      Note

        When at the end of a file or stream, repeated calls to `read()` returns the empty string since it's not considered an error. The empty string is never returned in other cases, unless nonblocking mode is used or `len` is zero.

      See also

        `read()`, `write_oob()`

      Method receive_fd

        ``void` receive_fd(`Stdio.Fd` `fd`)`

      Description

        Remote file descriptor reception handler.

      Parameter `fd`

        File descriptor received from the remote end of a `pipe()`. This object has been created by `fd_factory()`.

        This function is called from `read()` when a remote file descriptor has been received over a `PROP_SEND_FD` capable `pipe()`.

        The default implementation is just a prototype.

        Overload this function to enable reception of remote file descriptors.

      Note

        The capability of sending and receiving remote file descriptors is only available on some operating systems. This capability is indicated by the precence of `__HAVE_SEND_FD__`.

      See also

        `send_fd()`, `read()`, `fd_factory()`, `__HAVE_SEND_FD__`

      Method release_fd

        ``int` release_fd()`

      Description

        Returns the file descriptor number associated with this object, in addition to releasing it so that this object behaves as if closed. Other settings like callbacks and backend remain intact. `take_fd` can later be used to reinstate the file descriptor so that the state is restored.

      See also

        `query_fd()`, `take_fd()`

      Method removexattr

        ``void` removexattr(`string` `attr`)`

      Description

        Remove the specified extended attribute.

      Method seek

        ``int` seek(`int` `offset`)`
        ``int` seek(`int` `offset`, `string` `whence`)`

      Description

        The seek() function repositions the offset of the open file associated with the file descriptor fd to the argument `offset` according to the directive `whence` as follows:

        ``Stdio.SEEK_SET`` | The offset is set to `offset` bytes.
        ``Stdio.SEEK_CUR`` | The offset is set to its current location plus `offset` bytes.
        ``Stdio.SEEK_END`` | The offset is set to the size of the file plus `offset` bytes.

        If `whence` is not specified it is SEEK_SET if `offset` is positive, and if `offset` is negative SEEK_END.

        The seek() function on most operating systems allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a "hole") return null bytes ('\0') until data is actually written into the gap.

        Seeking file data and holes

        Stdio.SEEK_DATA and Stdio.SEEK_HOLE are nonstandard extensions present in Linux, Solaris, FreeBSD, and DragonFly BSD; they are proposed for inclusion in the next POSIX revision.

        ``Stdio.SEEK_DATA`` | Adjust the file offset to the next location in the file greater than or equal to offset containing data. If offset points to data, then the file offset is set to offset.
        ``Stdio.SEEK_HOLE`` | Adjust the file offset to the next hole in the file greater than or equal to offset. If offset points into the middle of a hole, then the file offset is set to offset. If there is no hole past offset, then the file offset is adjusted to the end of the file (i.e., there is an implicit hole at the end of any file).

        In both of the above cases, seek() fails if offset points past the end of the file.

        These operations allow applications to map holes in a sparsely allocated file. This can be useful for applications such as file backup tools, which can save space when creating backups and preserve holes, if they have a mechanism for discovering holes.

        For the purposes of these operations, a hole is a sequence of zeros that (normally) has not been allocated in the underlying file storage. However, a filesystem is not obliged to report holes, so these operations are not a guaranteed mechanism for mapping the storage space actually allocated to a file. (Furthermore, a sequence of zeros that actually has been written to the underlying storage may or may not be reported as a hole.)

        In the simplest implementation, a filesystem can support the operations by making SEEK_HOLE always return the offset of the end of the file, and making SEEK_DATA always return offset (i.e., even if the location referred to by offset is a hole, it can be considered to consist of data that is a sequence of zeros).

      Returns

        Upon successful completion, seek() returns the resulting offset location as measured in bytes from the beginning of the file. On error, the value (off_t) -1 is returned and `errno` is set to indicate the error.

      See also

        `tell()`

      Method send_fd

        ``void` send_fd(`Stdio.Fd` `fd`)`

      Description

        Queues an open file descriptor for sending to the other end of a stream.

      Note

        The actual sending is performed at the next successful call to `write()`, this is due to limitations in the system calls. This means that it isn't possible to send a file descriptor without also sending some in-band data.

        This operation is only supported on `pipe()`'s created with `PROP_SEND_FD`.

        This function is not available on all operating systems, check for `__HAVE_SEND_FD__`.

        The queue is emptied on successful `write()` and when the write direction is `close()`'d.

      See also

        `receive_fd()`, `write()`, `pipe()`, `read()`, `__HAVE_SEND_FD__`

      Method set_backend

        ``void` set_backend(`Pike.Backend` `backend`)`

      Description

        Set the backend used for the callbacks.

      Note

        The backend keeps a reference to this object only when it is in callback mode. So if this object hasn't got any active callbacks and it runs out of other references, it will still be destructed quickly (after closing, if necessary).

        Also, this object does not keep a reference to the backend.

      See also

        `query_backend`, `set_nonblocking`, `set_read_callback`, `set_write_callback`, `set_fs_event_callback`

      Method set_blocking

        ``void` set_blocking()`

      Description

        Sets this file to blocking operation.

        This is the inverse operation of `set_nonblocking()`.

      See also

        `set_nonblocking()`

      Method set_buffer

        ``void` set_buffer(`int` `bufsize`, `string` `mode`)`
        ``void` set_buffer(`int` `bufsize`)`

      Description

        Set internal socket buffer.

        This function sets the internal buffer size of a socket or stream.

        The second argument allows you to set the read or write buffer by specifying `"r"` or `"w"`.

      Note

        It is not guaranteed that this function actually does anything, but it certainly helps to increase data transfer speed when it does.

      See also

        `open_socket()`, `accept()`

      Method set_close_on_exec

        ``void` set_close_on_exec(`bool` `yes_no`)`

      Description

        Marks the file as to be closed in spawned processes.

        This function determines whether this file will be closed when calling exec().

        Default is that the file WILL be closed on exec except for stdin, stdout and stderr.

      See also

        `Process.create_process()`, `exec()`

      Method set_keepalive

        ``bool` set_keepalive(`bool` `on_off`)`

      Method set_nonblocking

        ``void` set_nonblocking()`

      Description

        Sets this file to nonblocking operation.

      Note

        Nonblocking operation is not supported on all Stdio.File objects. Notably it is not guaranteed to be supported on objects returned by `pipe()` unless `PROP_NONBLOCK` was specified in the call to `pipe()`.

      See also

        `set_blocking()`

      Method setxattr

        ``void` setxattr(`string` `attr`, `string` `value`, `int` `flags`)`

      Description

        Set the attribute `attr` to the value `value`.

        The flags parameter can be used to refine the semantics of the operation.

        `Stdio.XATTR_CREATE` specifies a pure create, which fails if the named attribute exists already.

        `Stdio.XATTR_REPLACE` specifies a pure replace operation, which fails if the named attribute does not already exist.

        By default (no flags), the extended attribute will be created if need be, or will simply replace the value if the attribute exists.

      Returns

        1 if successful, 0 otherwise, setting errno.

      Method stat

        ``Stat` stat()`

      Description

        Get status for an open file.

        This function returns the same information as the function `file_stat()`, but for the file it is called in. If file is not an open file, `0` (zero) is returned. Zero is also returned if file is a pipe or socket.

      Returns

        See `file_stat()` for a description of the return value.

      Note

        Prior to Pike 7.1 this function returned an array(int).

      See also

        `file_stat()`, `statat()`

      Method statat

        ``Stat` statat(`string` `path`, `void`|`bool` `symlink`)`

      Description

        Get status for a file relative an open directory.

        This function returns the same information as the function `file_stat()`, but relative to the file it is called in. If file is not an open file, `0` (zero) is returned. Zero is also returned if file is a pipe or socket.

      Returns

        See `file_stat()` for a description of the return value.

      Note

        Not available on all architectures, or in Pike 7.6 and earlier.

      See also

        `file_stat()`, `stat()`, `openat()`, `unlinkat()`

      Method sync

        ``bool` sync()`

      Description

        Flush buffers to disk.

      Returns

        Returns `0` (zero) and sets errno on failure.

        Returns `1` on success.

      Method take_fd

        ``void` take_fd(`int` `fd`)`

      Description

        Rehooks the given file descriptor number to be associated with this object. As opposed to using `open` with a file descriptor number, it will be closed by this object upon destruct or when `close` is called.

      See also

        `release_fd()`

      Method tcdrain

        ``bool` tcdrain()`

      Description

        Wait for transmission buffers to empty.

      Returns

        Returns `1` on success and `0` (zero) on failure.

      See also

        `tcflush()`

      Method tcflush

        ``bool` tcflush(`string`|`void` `flush_direction`)`

      Description

        Flush queued terminal control messages.

      Parameter `flush_direction`

        ``"TCIFLUSH"`` | Flush received but not read.
        ``"TCOFLUSH"`` | Flush written but not transmitted.
        ``"TCIOFLUSH"`` | Flush both of the above. Default.

      Returns

        Returns `1` on success and `0` (zero) on failure.

      See also

        `tcdrain()`

      Method tcgetattr
      Method tcsetattr

        ``mapping` tcgetattr()`
        ``int` tcsetattr(`mapping` `attr`)`
        ``int` tcsetattr(`mapping` `attr`, `string` `when`)`

      Description

        Gets/sets term attributes. The returned value/the `attr` parameter is a mapping on the form

        ``"ispeed"` : `int(-1..)`` | In baud rate.
        ``"ospeed"` : `int(-1..)`` | Out baud rate.
        ``"csize"` : `int(-1..-1)`|`int(5..8)`` | Character size in bits.
        ``"rows"` : `int`` | Terminal rows.
        ``"columns"` : `int`` | Terminal columns.

        ``flag_name` : `bool``

        The value of a named flag. The flag name is the string describing the termios flags (IGNBRK, BRKINT, IGNPAR, PARMRK, INPCK, ISTRIP, INLCR, IGNCR, ICRNL, IUCLC, IXON, IXANY, IXOFF, IMAXBEL, OPOST, OLCUC, ONLCR, OCRNL, ONOCR, ONLRET, OFILL, OFDEL, OXTABS, ONOEOT, CSTOPB, CREAD, PARENB, PARODD, HUPCL, CLOCAL, CRTSCTS, ISIG, ICANON, XCASE, ECHO, ECHOE, ECHOK, ECHONL, ECHOCTL, ECHOPRT, ECHOKE, FLUSHO, NOFLSH, TOSTOP, PENDIN). See the manpage for termios or other documentation for more information. All flags are not available on all platforms.

        ``character_name` : `int(8bit)`` | Sets the value of a control character (VINTR, VQUIT, VERASE, VKILL, VEOF, VTIME, VMIN, VSWTC, VSTART, VSTOP, VSUSP, VEOL, VREPRINT, VDISCARD, VWERASE, VLNEXT, VEOL2). All control characters are not available on all platforms.

        Negative values are not allowed as indata, but might appear in the result from `tcgetattr` when the actual value is unknown. `tcsetattr` returns 0 if failed.

        The argument `when` to `tcsetattr` describes when the changes are to take effect:

        ``"TCSANOW"`` | The change occurs immediately (default).
        ``"TCSADRAIN"`` | The change occurs after all output has been written.
        ``"TCSAFLUSH"`` | The change occurs after all output has been written, and empties input buffers.

      Example

            // setting the terminal in raw mode:
               Stdio.stdin->tcsetattr((["ECHO":0,"ICANON":0,"VMIN":0,"VTIME":0]));

      Note

        Unknown flags are ignored by `tcsetattr()`. `tcsetattr` always changes the attribute, so only include attributes that actually should be altered in the attribute mapping.

      Bugs

        Terminal rows and columns setting by `tcsetattr()` is not currently supported.

      See also

        `tcsetsize()`

      Method tcsendbreak

        ``bool` tcsendbreak(`int`|`void` `duration`)`

      Description

        Send a break signal.

      Parameter `duration`

        Duration to send the signal for. `0` (zero) causes a break signal to be sent for between 0.25 and 0.5 seconds. Other values are operating system dependent:

        SunOS

          The number of joined break signals as above.

        Linux, AIX, Digital Unix, Tru64

          The time in milliseconds.

        FreeBSD, NetBSD, HP-UX, MacOS

          The value is ignored.

        Solaris, Unixware

          The behavior is changed to be similar to `tcdrain()`.

      Returns

        Returns `1` on success and `0` (zero) on failure.

      Method tcsetsize

        ``bool` tcsetsize(`int` `rows`, `int` `cols`)`

      Description

        Set the number of rows and columns for a terminal.

      Returns

        Returns `1` on success and `0` (zero) on failure.

      See also

        `tcgetattr()`, `tcsetattr()`

      Method tell

        ``int` tell()`

      Description

        Returns the current offset in the file.

      See also

        `seek()`

      Method truncate

        ``bool` truncate(`int` `length`)`

      Description

        Truncate a file.

        Truncates the file to the specified length `length`.

      Returns

        Returns `1` on success, and `0` (zero) on failure.

      See also

        `open()`

      Method trylock

        ``Stdio.FileLockKey` trylock()`
        ``Stdio.FileLockKey` trylock(`bool` `is_recursive`)`

      Description

        Attempts to place a file lock on this file.

      See also

        `lock()`

      Method unlinkat

        ``int` unlinkat(`string` `f`)`

      Description

        Remove a file or directory relative to an open file.

      Returns

        Returns `0` (zero) on failure, `1` otherwise.

      See also

        `rm()`, `openat()`, `statat()`

      Method write

        ``int` write(`string` `data`)`
        ``int` write(`string` `format`, `mixed` ... `extras`)`
        ``int` write(`array`(`string`) `data`)`
        ``int` write(`array`(`string`) `format`, `mixed` ... `extras`)`

      Description

        Write data to a file or a stream.

        If there are any file descriptors that have been queued for sending (with `send_fd()`), they will be sent.

      Parameter `data`

        Data to write.

        If `data` is an array of strings, they are written in sequence.

      Parameter `format`
      Parameter `extras`

        If more than one argument is given, `sprintf()` is used to format them using `format`. If `format` is an array, the strings in it are concatenated and the result is used as format string.

      Returns

        Writes `data` and returns the number of bytes that were actually written.

        ``(1..)``

        The number of bytes successfully written to the OS buffers.

        This can be less than the size of the given data if eg:

        - Some data was written successfully and then something went wrong.

          If only some data was written due to an error and that error persists, then a later call to `write()` will fail and return `-1`.

        - Nonblocking mode is used and not all data could be written without blocking.

        ``0``

        No bytes were written. This may be due to

        - `data` or the formatted data being the empty string.

        - Nonblocking mode is used and no data could be written without blocking.

        ``-1`` | Something went wrong and no bytes were written.

        If everything went fine, a call to `errno()` directly afterwards returns zero.

      Note

        Writing of wide strings is not supported. You have to encode the data somehow, e.g. with `string_to_utf8` or with one of the charsets supported by `Charset.encoder`.

      See also

        `read()`, `write_oob()`, `send_fd()`

      Method write_oob

        ``int` write_oob(`string` `data`)`
        ``int` write_oob(`string` `format`, `mixed` ... `extras`)`

      Description

        Write out-of-band data to a stream.

        Writes out-of-band data to a stream and returns how many bytes that were actually written. It can be less than the size of the given data if some data was written successfully and then something went wrong.

        -1 is returned if something went wrong and no bytes were written. If only some data was written due to an error and that error persists, then a later call to `write_oob()` fails and returns -1.

        If everything went fine, a call to `errno()` directly afterwards returns zero.

        If more than one argument is given, `sprintf()` is used to format them.

      Note

        Out-of-band data was not supported in Pike 0.5 and earlier, and not in Pike 0.6 through 7.4 if they were compiled with the option `'--without-oob'`.

      Note

        It is not guaranteed that all out-of-band data sent from the other end is received. Most streams only allow for a single byte of out-of-band data at a time. Some streams sends the rest of the data as ordinary data.

      See also

        `read_oob()`, `write()`

    ## Class Stdio.Fd_ref

      Description

        Proxy class that contains stub functions that call the corresponding functions in `Fd`.

        Used by `Stdio.File`.

      Note

        This is not the class you want. Use `Stdio.File` and friends instead.

      See also

        `Stdio.File`, `Stdio.FILE`, `_Stdio.Fd`

      Variable _fd

        ``Fd` Stdio.Fd_ref._fd`

      Description

        Object to which called functions are relayed.

      Inherit Fd

        `inherit Fd : Fd`

      Description

        Fake inherit to propagate the documentation from `_Stdio.Fd`.

    ## Class Stdio.NonblockingStream

      Description

        The Stdio.NonblockingStream API.

        This class exists purely for typing reasons.

        Use in types in place of `Stdio.File` where nonblocking and/or blocking stream-oriented I/O is done with the object.

      See also

        `Stream`, `BlockFile`, `File`, `FILE`

      Inherit Stream

        `inherit Stream : Stream`

      Method set_blocking

        ``void` set_blocking()`

      Method set_read_callback
      Method set_write_callback
      Method set_close_callback
      Method set_fs_event_callback

        ``NonblockingStream` set_read_callback(`function`(:`void`) `f`, `mixed` ... `rest`)`
        ``NonblockingStream` set_write_callback(`function`(:`void`) `f`, `mixed` ... `rest`)`
        ``NonblockingStream` set_close_callback(`function`(:`void`) `f`, `mixed` ... `rest`)`
        ``NonblockingStream` set_fs_event_callback(`function`(:`void`) `f`, `int` `event_mask`, `mixed` ... `rest`)`

      Method set_nonblocking

        ``void` set_nonblocking(`function`(:`void`) `a`, `function`(:`void`) `b`, `function`(:`void`) `c`, `function`(:`void`)|`void` `d`, `function`(:`void`)|`void` `e`)`

      Method set_read_oob_callback
      Method set_write_oob_callback

        ``optional` `NonblockingStream` set_read_oob_callback(`function`(:`void`) `f`, `mixed` ... `rest`)`
        ``optional` `NonblockingStream` set_write_oob_callback(`function`(:`void`) `f`, `mixed` ... `rest`)`

    ## Class Stdio.Stat

      Description

        This object is used to represent file status information from e.g. `file_stat()`.

        It contains the following items usually found in a C `struct stat`:

        mode

          File mode (see `mknod(2)`).

        size

          File size in bytes.

        uid

          User ID of the file's owner.

        gid

          Group ID of the file's owner.

        atime

          Time of last access in seconds since 00:00:00 UTC, 1970-01-01.

        mtime

          Time of last data modification.

        ctime

          Time of last file status change.

        atime_nsec

          Time of last access in nanoseconds, added to atime to get sub-second time

        mtime_nsec

          Time of last modification in nanoseconds, added to mtime to get sub-second time

        ctime_nsec

          Time of last file status change in nanoseconds, added to ctime to get sub-second time

        ino

          Inode number.

        nlink

          Number of links.

        dev

          ID of the device containing a directory entry for this file.

        rdev

          ID of the device.

        It also contains some items that correspond to the C `IS*` macros:

        isreg

          Set if the file is a regular file.

        isdir

          Set if the file is a directory.

        islnk

          Set if the file is a symbolic link. Note that symbolic links are normally followed by the stat functions, so this might only be set if you turn that off, e.g. by giving a nonzero second argument to `file_stat()`.

        isfifo

          Set if the file is a FIFO (aka named pipe).

        issock

          Set if the file is a socket.

        ischr

          Set if the file is a character device.

        isblk

          Set if the file is a block device.

        There are also some items that provide alternative representations of the above:

        type

          The type as a string, can be any of `"reg"`, `"dir"`, `"lnk"`, `"fifo"`, `"sock"`, `"chr"`, `"blk"`, and `"unknown"`.

        mode_string

          The file mode encoded as a string in `ls -l` style, e.g. `"drwxr-xr-x"`.

        Note that some items might not exist or have meaningful values on some platforms.

        Additionally, the object may be initialized from or casted to an `array` on the form of a 'traditional' LPC stat-array, and it's also possible to index the object directly with integers as if it were such an array. The stat-array has this format:

        Array
        ``int` `0`` | File mode, same as `mode`.
        ``int` `1`` | If zero or greater, the file is a regular file and this is its size in bytes. If less than zero it gives the type: -2=directory, -3=symlink and -4=device.
        ``int` `2`` | Time of last access, same as `atime`.
        ``int` `3`` | Time of last data modification, same as `mtime`.
        ``int` `4`` | Time of last file status change, same as `ctime`.
        ``int` `5`` | User ID of the file's owner, same as `uid`.
        ``int` `6`` | Group ID of the file's owner, same as `gid`.

        It's possible to modify the stat struct by assigning values to the items. They essentially work as variables, although some of them affect others, e.g. setting `isdir` clears `isreg` and setting `mode_string` changes many of the other items.

      Method cast

        `(`mapping`(`string`:`int`))Stdio.Stat()
        (`array`)Stdio.Stat()
        `

      Description

        Convert the stat object to a mapping or array.

      Method create

        `Stdio.Stat Stdio.Stat(`void`|`object`|`array` `stat`)`

      Description

        A new `Stdio.Stat` object can be initialized in two ways:

        - `stat` is an object, typically another `Stdio.Stat`. The stat info is copied from the object by getting the values of `mode`, `size`, `atime`, `mtime`, `ctime`, `uid`, `gid`, `dev`, `ino`, `nlink`, and `rdev`.

        - `stat` is a seven element array on the 'traditional' LPC stat-array form (see the class doc).

    ## Class Stdio.Stream

      Description

        The Stdio.Stream API.

        This class exists purely for typing reasons.

        Use in types in place of `Stdio.File` where only blocking stream-oriented I/O is done with the object.

        This class lists the minimum functionality guaranteed to exist in all Stream objects.

      See also

        `NonblockingStream`, `BlockFile`, `File`, `FILE`

      Method close

        ``void` close()`

      Method read

        ``string` read(`int` `nbytes`)`

      Method read_oob
      Method write_oob
      Method tcgetattr
      Method tcsetattr

        ``optional` `string` read_oob(`int` `nbytes`)`
        ``optional` `int` write_oob(`string` `data`)`
        ``optional` `mapping`(`string`:`int`) tcgetattr()`
        ``optional` `int` tcsetattr(`mapping`(`string`:`int`) `attr`, `string`|`void` `when`)`

      Method write

        ``int` write(`string` `data`)`

    ## Class Stdio.sendfile

      Description

        Send `headers + from_fd[off..off+len-1] + trailers` to `to_fd` asyncronously.

      Note

        This is the low-level implementation, which has several limitations. You probably want to use `Stdio.sendfile()` instead.

      See also

        `Stdio.sendfile()`

      Method create

        `Stdio.sendfile Stdio.sendfile(`array`(`string`) `headers`, `object` `from`, `int` `offset`, `int` `len`, `array`(`string`) `trailers`, `object` `to`, `function`(:`void`) `callback`, `mixed` ... `args`)`

      Description

        Low-level implementation of `Stdio.sendfile()`.

        Sends `headers` followed by `len` bytes starting at `offset` from the file `from` followed by `trailers` to the file `to`. When completed `callback` will be called with the total number of bytes sent as the first argument, followed by `args`.

        Any of `headers`, `from` and `trailers` may be left out by setting them to `0`.

        Setting `offset` to `-1` means send from the current position in `from`.

        Setting `len` to `-1` means send until `from`'s end of file is reached.

      Note

        Don't use this class directly! Use `Stdio.sendfile()` instead.

        In Pike 7.7 and later the `callback` function will be called from the backend associated with `to`.

      Note

        May use blocking I/O and thus trigger process being killed with `SIGPIPE` when the other end closes the connection. Add a call to `signal()` to avoid this.

      See also

        `Stdio.sendfile()`