9. I/O

9.1. File system manipulation


Methodaccess

intaccess(stringpath, string|voidmode)

Description

access() checks if the calling process can access the file path. Symbolic links are dereferenced.

Parameter mode

The mode specifies the accessibility checks to be performed, and is either not specified or empty, in which case access() just tests if the file exists, or one or more of the characters "rwx".

r, w, and x test whether the file exists and grants read, write, and execute permissions, respectively.

The check is done using the calling process's real UID and GID, rather than the effective IDs as is done when actually attempting an operation (e.g., open(2)) on the file. This allows set-user-ID programs to easily determine the invoking user's authority.

If the calling process is privileged (i.e., its real UID is zero), then an X_OK check is successful for a regular file if execute permission is enabled for any of the file owner, group, or other.

Returns
1

When the file is accessible using the given permissions.

0

When the file is not accessible, in which case errno is set to one of the following values:

EACCESS

Access denied.

ELOOP

Too many symbolic links.

ENAMETOOLONG

The path is too long.

ENOENT

The file does not exist.

ENOTDIR

One of the directories used in path is not, in fact, a directory.

EROFS

The filesystem is read only and write access was requested.

Other errors can occur, but are not directly related to the requested path, such as ENOMEM, etc.

See also

errno(), Stdio.File


Methodcd

intcd(strings)

Description

Change the current directory for the whole Pike process.

Returns

Returns 1 for success, 0 (zero) otherwise.

See also

getcwd()


Methodgetcwd

stringgetcwd()

Description

Returns the current working directory.

See also

cd()


Methodget_dir

array(string) get_dir(void|stringdirname)

Description

Returns an array of all filenames in the directory dirname, or 0 (zero) if the directory does not exist. When no dirname is given, current work directory is used.

See also

mkdir(), cd()


Methodmkdir

intmkdir(stringdirname, void|intmode)

Description

Create a directory.

If mode is specified, it's will be used for the new directory after being &'ed with the current umask (on OS'es that support this).

Returns

Returns 0 (zero) on failure, 1 otherwise.

See also

rm(), cd(), Stdio.mkdirhier()


Methodcp

intcp(stringfrom, stringto)

Description

Copies the file from to the new position to. This is an alias for Stdio.cp.


Methodmv

intmv(stringfrom, stringto)

Description

Rename or move a file or directory.

If the destination already exists, it will be replaced. Replacement often only works if to is of the same type as from, i.e. a file can only be replaced by another file and so on. Also, a directory will commonly be replaced only if it's empty.

On some OSs this function can't move directories, only rename them.

Returns

Returns 0 (zero) on failure, 1 otherwise. Call errno() to get more error info on failure.

See also

rm()


Methodrm

intrm(stringf)

Description

Remove a file or directory.

Returns

Returns 0 (zero) on failure, 1 otherwise.

Note

May fail with errno() set to EISDIR or ENOTDIR if the file has changed to a directory during the call or the reverse.

See also

Stdio.File()->unlinkat(), mkdir(), Stdio.recursive_rm()


Methodfile_truncate

intfile_truncate(stringfile, intlength)

Description

Truncates the file file to the length specified in length.

Returns

Returns 1 if ok, 0 if failed.

9.2. Path manipulation


Methodbasename

stringbasename(stringpath)

Description

Returns the last segment of a path.

See also

dirname(), explode_path()


Methoddirname

stringdirname(stringpath)

Description

Returns all but the last segment of a path. Some example inputs and outputs:

ExpressionValue
dirname("/a/b")"/a"
dirname("/a/")"/a"
dirname("/a")"/"
dirname("/")"/"
dirname("")""
See also

basename(), explode_path()


Methodcombine_path
Methodcombine_path_unix
Methodcombine_path_nt
Methodcombine_path_amigaos

stringcombine_path(stringpath, string ... paths)
stringcombine_path_unix(stringpath, string ... paths)
stringcombine_path_nt(stringpath, string ... paths)
stringcombine_path_amigaos(stringpath, string ... paths)

Description

Concatenate a number of paths to a straightforward path without any "//", "/.." or "/.". If any path argument is absolute then the result is absolute and the preceding arguments are ignored. If the result is relative then it might have leading ".." components. If the last nonempty argument ends with a directory separator then the result ends with that too. If all components in a relative path disappear due to subsequent ".." components then the result is ".".

combine_path_unix() concatenates in UNIX style, which also is appropriate for e.g. URL:s ("/" separates path components and absolute paths start with "/"). combine_path_nt() concatenates according to NT filesystem conventions ("/" and "\" separates path components and there might be a drive letter in front of absolute paths). combine_path_amigaos() concatenates according to AmigaOS filesystem conventions.

combine_path() is equivalent to combine_path_unix() on UNIX-like operating systems, and equivalent to combine_path_nt() on NT-like operating systems, and equivalent to combine_path_amigaos() on AmigaOS-like operating systems.

See also

getcwd(), Stdio.append_path()


Methodexplode_path

array(string) explode_path(stringp)

Description

Split a path p into its components.

This function divides a path into its components. This might seem like it could be done by dividing the string on <tt>"/"</tt>, but that will not work on some operating systems. To turn the components back into a path again, use combine_path().

9.3. Status


Methodfile_stat

Stdio.Statfile_stat(stringpath, void|boolsymlink)

Description

Stat a file.

If the argument symlink is 1 symlinks will not be followed.

Returns

If the path specified by path doesn't exist 0 (zero) will be returned.

Otherwise an object describing the properties of path will be returned.

Note

In Pike 7.0 and earlier this function returned an array with 7 elements. The old behaviour can be simulated with the following function:

array(int) file_stat(string path,void|int(0..1) symlink){
  File.Stat st = predef::file_stat(path, symlink);if(!st)return 0;return(array(int))st;}
See also

Stdio.Stat, Stdio.File->stat()


Methodfilesystem_stat

mapping(string:int) filesystem_stat(stringpath)

Description

Returns a mapping describing the properties of the filesystem containing the path specified by path.

Returns

If a filesystem cannot be determined 0 (zero) will be returned.

Otherwise a mapping(string:int) with the following fields will be returned:

"blocksize" : int

Size in bytes of the filesystem blocks.

"blocks" : int

Size of the entire filesystem in blocks.

"bfree" : int

Number of free blocks in the filesystem.

"bavail" : int

Number of available blocks in the filesystem. This is usually somewhat less than the "bfree" value, and can usually be adjusted with eg tunefs(1M).

"files" : int

Total number of files (aka inodes) allowed by this filesystem.

"ffree" : int

Number of free files in the filesystem.

"favail" : int

Number of available files in the filesystem. This is usually the same as the "ffree" value, and can usually be adjusted with eg tunefs(1M).

"fsname" : string

Name assigned to the filesystem. This item is not available on all systems.

"fstype" : string

Type of filesystem (eg "nfs"). This item is not available on all systems. For some more uncommon filesystems this may be an integer representing the magic number for the filesystem type (cf statfs(2) on eg Linux systems).

Note

Please note that not all members are present on all OSs.

See also

file_stat()

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
int0

File mode, same as mode.

int1

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.

int2

Time of last access, same as atime.

int3

Time of last data modification, same as mtime.

int4

Time of last file status change, same as ctime.

int5

User ID of the file's owner, same as uid.

int6

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_equal

boolequal(Stdio.Statfrom, mixedother)

Description

Compare this object with another Stat object.

Returns

Returns 1 if other is a Stat object with the same content, and 0 (zero) otherwise.


Methodcast

(mapping(string:int))Stdio.Stat()
(array)Stdio.Stat()

Description

Convert the stat object to a mapping or array.


Methodcreate

Stdio.StatStdio.Stat(void|object|arraystat)

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).

9.4. Error handling


Methoderrno

interrno()

Description

This function returns the system error from the last file operation.

Note

Note that you should normally use Stdio.File->errno() instead.

See also

Stdio.File->errno(), strerror()


Methodstrerror

stringstrerror(interrno)

Description

This function returns a description of an error code. The error code is usually obtained from eg Stdio.File->errno().

Note

On some platforms the string returned can be somewhat nondescriptive.

9.5. Files and sockets

Class Stdio.File

Annotations
@Pike.Annotations.Implements(NonblockingStream)
@Pike.Annotations.Implements(BlockFile)
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


Methodassign

intassign(File|Fdo)

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()


Methodasync_connect

intasync_connect(stringhost, int|stringport, 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 to open a socket, 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()


Methodclose

intclose()
intclose(stringdirection)

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


Methodconnect

variantintconnect(stringhost, int(0..)|stringport)
variantintconnect(stringhost, int(0..)|stringport, stringclient, int(0..)|stringclient_port)
variantstringconnect(stringhost, int(0..)|stringport, stringdata)
variantstringconnect(stringhost, int(0..)|stringport, int(0..0)|stringclient, int(0..)|stringclient_port, stringdata)

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 advisable 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()


Methodconnect_unix

intconnect_unix(stringpath)

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


Methodcreate

Stdio.FileStdio.File()
Stdio.FileStdio.File(stringfilename)
Stdio.FileStdio.File(stringfilename, stringmode)
Stdio.FileStdio.File(stringfilename, stringmode, intmask)
Stdio.FileStdio.File(stringdescriptorname)
Stdio.FileStdio.File(intfd)
Stdio.FileStdio.File(intfd, stringmode)

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,


Methoddup

Filedup()

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()


Methoderrno

interrno()

Description

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


InheritFd

optional inherit Fd : Fd


Methodline_iterator

String.SplitIterator|LineIteratorline_iterator(int|voidtrim)

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.


Methodopen

intopen(stringfilename, stringmode)
intopen(stringfilename, stringmode, intmask)

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()


Methodopen_socket

intopen_socket(int|string|voidport, string|voidaddress, int|string|voidfamily_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()


Methodopenat

Fileopenat(stringfilename)
Fileopenat(stringfilename, stringmode)
Fileopenat(stringfilename, stringmode, intmask)

Description

Open a file relative to an open directory.

See also

File.statat(), File.unlinkat()


Methodopenpt

intopenpt(stringmode)

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()


Methodpipe

Filepipe(void|intrequired_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


Methodquery_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.Buffer0

The current input buffer.

Stdio.Buffer1

The current output buffer.

See also

set_buffer_mode()


Methodquery_read_callback
Methodquery_write_callback
Methodquery_read_oob_callback
Methodquery_write_oob_callback
Methodquery_close_callback
Methodquery_callbacks

read_callback_tquery_read_callback()
write_callback_tquery_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


Methodquery_id

mixedquery_id()

Description

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

See also

set_id()


Methodread

string(8bit)read(int|voidnbytes, bool|voidnot_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()


Methodread_function

function(:string) read_function(intnbytes)

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.


Methodsend_fd

voidsend_fd(File|Fdfile)


Methodset_blocking

voidset_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()


Methodset_nonblocking_keep_callbacks
Methodset_blocking_keep_callbacks

voidset_nonblocking_keep_callbacks()
voidset_blocking_keep_callbacks()

Description

Toggle between blocking and nonblocking, without changing the callbacks.

See also

set_nonblocking(), set_blocking()


Methodset_buffer_mode

voidset_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. If this buffer is non-empty, its contents will be returned after any already received data.

Parameter out

Output buffer. If this buffer is non-empty, its contents will be sent after any data already queued for sending.

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

query_buffer_mode()


Methodset_callbacks

voidset_callbacks(read_callback_t|voidread_cb, write_callback_t|voidwrite_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


Methodset_read_callback
Methodset_write_callback
Methodset_read_oob_callback
Methodset_write_oob_callback
Methodset_close_callback
Methodset_fs_event_callback

voidset_read_callback(function(mixed, string:int) read_cb)
voidset_read_callback(function(mixed, Buffer:int) read_cb)
voidset_write_callback(function(mixed:int) write_cb)
voidset_write_callback(function(mixed, Buffer:int) write_cb)
voidset_read_oob_callback(function(mixed, string:int) read_oob_cb)
voidset_write_oob_callback(function(mixed:int) write_oob_cb)
voidset_close_callback(function(mixed:int) close_cb)
voidset_fs_event_callback(function(mixed, int:int) fs_event_cb, intevent_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


Methodset_id

voidset_id(mixedid)

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()


Methodset_nonblocking

voidset_nonblocking(read_callback_tread_callback, write_callback_twrite_callback, function(mixed:int) close_callback)
voidset_nonblocking(read_callback_tread_callback, write_callback_twrite_callback, function(mixed:int) close_callback, function(mixed, string:int) read_oob_callback, function(mixed:int) write_oob_callback)
voidset_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.FILEa;
foreach( a; index; value ) or
protectedobject_get_iterator()

Description

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

See also

line_iterator()


Methodgetchar

localintgetchar()

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.


Methodgets

stringgets(bool|voidnot_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()


Inheritfile

inherit File : file


Methodline_iterator

objectline_iterator(int|voidtrim)

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()


Methodngets

array(string) ngets(void|int(1..)n, bool|voidnot_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.


Methodopenat

FILEopenat(stringfilename)
FILEopenat(stringfilename, stringmode)
FILEopenat(stringfilename, stringmode, intmask)

Description

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

See also

Stdio.File()->openat()


Methodpipe

FILEpipe(void|intflags)

Description

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

See also

Stdio.File()->pipe()


Methodprintf

intprintf(stringformat, mixed ... data)

Description

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

See also

write(), sprintf()


Methodread

stringread(int|voidbytes, void|boolnow)

Description

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

See also

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


Methodset_charset

voidset_charset(string|voidcharset)

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.


Methodungets

voidungets(strings)

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()


Methodunread

voidunread(strings)

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()


Methodwrite

intwrite(array(string)|stringwhat, mixed ... fmt)

Description

Write what with support for output_conversion.

See also

Stdio.File()->write()

9.6. Ports and UDP

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.


Methodaccept

Fileaccept()

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, fd_factory()


Methodcreate

Stdio.PortStdio.Port()
Stdio.PortStdio.Port(int|stringport)
Stdio.PortStdio.Port(int|stringport, function(:void) accept_callback)
Stdio.PortStdio.Port(int|stringport, function(:void) accept_callback, stringip)
Stdio.PortStdio.Port("stdin")
Stdio.PortStdio.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, and is equivalent to creating a port and initializing it with listen_fd(0).

See also

bind


Methodfd_factory

protectedFdfd_factory()

Description

Factory creating empty Fd objects.

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

The default implementation returns the Fd inherit in an empty File object.

See also

accept()


Inherit_port

inherit _port : _port

Class Stdio.UDP

Description

UDP (User Datagram Protocol) handling.


InheritUDP

inherit _Stdio.UDP : UDP


Methodset_nonblocking

UDPset_nonblocking()
UDPset_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.


Methodset_read_callback

UDPset_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()

9.7. Terminal I/O

Module Stdio.Terminfo


MethodgetFallbackTerm

protectedTermcapgetFallbackTerm(stringterm)

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


MethodgetTerm

TermcapgetTerm(string|voidterm)

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


MethodgetTermcap

TermcapgetTermcap(stringterm)

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


MethodgetTerminfo

TerminfogetTerminfo(stringterm)

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


Methodis_tty

intis_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.


Methodcreate

Stdio.Terminfo.MetaTerminfoDBStdio.Terminfo.MetaTerminfoDB(array(TerminfoDB|string)|voiddbs)

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.


Variablealiases

array(string) Stdio.Terminfo.Termcap.aliases


Methodcreate

Stdio.Terminfo.TermcapStdio.Terminfo.Termcap(stringcap, TermcapDB|voidtcdb, int|voidmaxrecurse)


InheritTermMachine

inherit TermMachine : TermMachine


Methodtputs

stringtputs(strings)

Description

Put termcap string

Class Stdio.Terminfo.TermcapDB

Description

Termcap database

Class Stdio.Terminfo.Terminfo

Description

Terminfo terminal description object


Variablealiases

array(string) Stdio.Terminfo.Terminfo.aliases


Methodcreate

Stdio.Terminfo.TerminfoStdio.Terminfo.Terminfo(stringfilename)


InheritTermMachine

inherit TermMachine : TermMachine


Methodtputs

stringtputs(strings)

FIXME

Document this function

Class Stdio.Terminfo.TerminfoDB

Description

Terminfo database for a single directory.

Class Stdio.Readline


Methodadd_to_kill_ring

voidadd_to_kill_ring(strings)

FIXME

Document this function


Methodcreate

Stdio.ReadlineStdio.Readline(object|voidinfd, object|string|voidinterm, object|voidoutfd, object|string|voidoutterm)

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.


Methoddelete

voiddelete(intp1, intp2)

FIXME

Document this function


Methoddelta_history

voiddelta_history(intd)

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.


Methodedit

stringedit(stringdata, string|voidlocal_prompt, array(string)|voidattrs)

FIXME

Document this function


Methodenable_history

voidenable_history(array(string)|History|inthist)

FIXME

Document this function


Methodeof

voideof()

FIXME

Document this function


Methodget_history

Historyget_history()

FIXME

Document this function


Methodget_input_controller

InputControllerget_input_controller()

Description

get current input control object

Returns

Terminal input controller object


Methodget_output_controller

OutputControllerget_output_controller()

Description

get current output control object

Returns

Terminal output controller object


Methodget_prompt

stringget_prompt()

Description

Return the current prompt string.


Methodgetcursorpos

intgetcursorpos()

FIXME

Document this function


Methodgetmark

intgetmark()

FIXME

Document this function


Methodgettext

stringgettext()

FIXME

Document this function


Methodhistory

voidhistory(intn)

FIXME

Document this function


Methodinsert

voidinsert(strings, intp)

FIXME

Document this function


Methodkill

voidkill(intp1, intp2)

FIXME

Document this function


Methodkill_ring_yank

stringkill_ring_yank()

FIXME

Document this function


Methodlist_completions

voidlist_completions(array(string) c)

FIXME

Document this function


Methodmessage

voidmessage(stringmsg)

Description

Print a message to the output device


Methodnewline

stringnewline()

FIXME

Document this function


Methodpointmark

array(int) pointmark()

FIXME

Document this function


Methodread

stringread(string|voidprompt, array(string)|voidattrs)

FIXME

Document this function


Methodredisplay

voidredisplay(intclear, int|voidnobackup)

FIXME

Document this function


Methodregion

stringregion(int ... args)

FIXME

Document this function


Methodset_blocking

voidset_blocking()

FIXME

Document this function


Methodset_echo

voidset_echo(intonoff)

Description

Set text echo on or off.

Parameter onoff

1 for echo, 0 for no echo.


Methodset_nonblocking

voidset_nonblocking(function(:void) f)

FIXME

Document this function


Methodset_prompt

stringset_prompt(stringnewp, array(string)|voidnewattrs)

Description

Set the prompt string.

Parameter newp

New prompt string

Parameter newattrs

Terminal attributes


Methodsetcursorpos

intsetcursorpos(intp)

FIXME

Document this function


Methodsetmark

intsetmark(intp)

FIXME

Document this function


Methodwrite

voidwrite(stringmsg, void|intword_wrap)

FIXME

Document this function

Class Stdio.Readline.DefaultEditKeys


Methodbackward_char

voidbackward_char()


Methodbackward_delete_char

voidbackward_delete_char()


Methodbackward_kill_word

voidbackward_kill_word()


Methodbackward_word

voidbackward_word()


Methodbeginning_of_line

voidbeginning_of_line()


Methodcapitalize_word

voidcapitalize_word()


Methodclear_screen

voidclear_screen()


Methodcreate

Stdio.Readline.DefaultEditKeysStdio.Readline.DefaultEditKeys(objectreadline)


Methoddelete_char

voiddelete_char()


Methoddelete_char_or_eof

voiddelete_char_or_eof()


Methoddown_history

voiddown_history()


Methoddowncase_word

voiddowncase_word()


Methodend_of_line

voidend_of_line()


Methodforward_char

voidforward_char()


Methodforward_word

voidforward_word()


Methodkill_line

voidkill_line()


Methodkill_region

voidkill_region()


Methodkill_ring_save

voidkill_ring_save()


Methodkill_whole_line

voidkill_whole_line()


Methodkill_word

voidkill_word()


Methodnewline

voidnewline()


Methodquoted_insert

voidquoted_insert()


Methodredisplay

voidredisplay()


Methodself_insert_command

voidself_insert_command(stringstr)


Methodset_default_bindings

protectedvoidset_default_bindings()


Methodset_mark

voidset_mark()


Methodswap_mark_and_point

voidswap_mark_and_point()


Methodtranspose_chars

voidtranspose_chars()


Methodup_history

voidup_history()


Methodupcase_word

voidupcase_word()


Methodyank

voidyank()

Class Stdio.Readline.History


Methodcreate

Stdio.Readline.HistoryStdio.Readline.History(intmaxhist, void|array(string) hist)


Methodencode

stringencode()


Methodfinishline

voidfinishline(stringtext)


Methodget_history_num

intget_history_num()


Methodhistory

stringhistory(intn, stringtext)


Methodinitline

voidinitline()


Methodpop

boolpop(string|voidtext)

Description

Pop the last string off the history, discarding it. If text is provided, will only pop that string. Returns 1 if a string was removed, 0 if not.


Methodset_max_history

voidset_max_history(intmaxhist)

Class Stdio.Readline.InputController

FIXME

Ought to have support for charset conversion.


Methodbind

function(:void) bind(stringk, function(:void) f)


Methodbindstr

function(:void) bindstr(stringstr, function(:void) f)


Methodbindtc

function(:void) bindtc(stringcap, function(:void) f)


Methodcreate

Stdio.Readline.InputControllerStdio.Readline.InputController(object|void_infd, object|string|void_term)


Methoddisable

intdisable()


Methodenable

intenable(int ... e)


Methodgetbinding

function(:void) getbinding(stringk, stringcap)


Methodgetbindings

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


Methodgetbindingstr

function(:void) getbindingstr(stringstr)


Methodgetbindingtc

function(:void) getbindingtc(stringcap)


Methodgrabnextkey

voidgrabnextkey(function(:void) g)


Methodisenabled

intisenabled()


Methodnullbindings

voidnullbindings()

Description

Clears the bindings.


Methodparsekey

stringparsekey(stringk)


Methodrun_blocking

intrun_blocking()


Methodset_close_callback

voidset_close_callback(function(:int) ccb)


Methodunbind

function(:void) unbind(stringk)


Methodunbindstr

function(:void) unbindstr(stringstr)


Methodunbindtc

function(:void) unbindtc(stringcap)

Class Stdio.Readline.OutputController

FIXME

Ought to have support for charset conversion.


Methodbeep

voidbeep()


Methodbol

voidbol()


Methodcheck_columns

intcheck_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


Methodclear

voidclear(int|voidpartial)


Methodcreate

Stdio.Readline.OutputControllerStdio.Readline.OutputController(.File|void_outfd, .Terminfo.Termcap|string|void_term)


Methoddisable

voiddisable()


Methodenable

voidenable()


Methoderase

voiderase(strings)


Methodget_number_of_columns

intget_number_of_columns()

Description

Returns the width of the terminal.

Note

Does not check the width of the terminal.

See also

check_columns


Methodlow_erase

voidlow_erase(intn)


Methodlow_move_backward

voidlow_move_backward(intn)


Methodlow_move_downward

voidlow_move_downward(intn)


Methodlow_move_forward

voidlow_move_forward(intn)


Methodlow_move_upward

voidlow_move_upward(intn)


Methodlow_write

voidlow_write(strings, void|intword_break)


Methodmove_backward

voidmove_backward(strings)


Methodmove_forward

voidmove_forward(strings)


Methodnewline

voidnewline()


Methodturn_off

voidturn_off(string ... atts)

Description

Set the provided attributes to off.


Methodturn_on

voidturn_on(string ... atts)

Description

Set the provided attributes to on.


Methodwrite

voidwrite(strings, void|intword_break, void|inthide)

9.8. Other

Module Stdio


ConstantDATA_CHUNK_SIZE

final constantint Stdio.DATA_CHUNK_SIZE

Description

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


ConstantTCSADRAIN

constantstring Stdio.TCSADRAIN

Description

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

Change after all output has been written.


ConstantTCSAFLUSH

constantstring Stdio.TCSAFLUSH

Description

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

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


ConstantTCSANOW

constantstring Stdio.TCSANOW

Description

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

Change immediately.


Methodappend_file

intappend_file(stringfilename, stringstr, int|voidaccess)

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()


Methodappend_path
Methodappend_path_unix
Methodappend_path_nt

stringappend_path(stringabsolute, string ... relative)
stringappend_path_unix(stringabsolute, string ... relative)
stringappend_path_nt(stringabsolute, 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()


Methodasync_cp

voidasync_cp(stringfrom, stringto, 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()


Methodconvert_modestring2int

intconvert_modestring2int(stringmode_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


Methodcp

intcp(stringfrom, stringto)

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.


Methodexist

intexist(stringpath)

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()


Methodfile_equal

intfile_equal(stringfile_1, stringfile_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.


Methodfile_size

intfile_size(stringfilename)

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()


Inherit_Stdio

inherit _Stdio : _Stdio


Methodis_dir

intis_dir(stringpath)

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()


Methodis_file

intis_file(stringpath)

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()


Methodis_link

intis_link(stringpath)

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()


Methodmkdirhier

intmkdirhier(stringpathname, void|intmode)

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()


Methodperror

voidperror(strings)

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()


Methodread_bytes

stringread_bytes(stringfilename, intstart, intlen)
stringread_bytes(stringfilename, intstart)
stringread_bytes(stringfilename)

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()


Typedefread_callback_t

local typedeffunction(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.


Methodread_file

stringread_file(stringfilename)
stringread_file(stringfilename, intstart, intlen)

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()


Methodrecursive_mv

intrecursive_mv(stringfrom, stringto)

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_rmcp


Methodrecursive_rm

intrecursive_rm(stringpath)

Description

Remove a file or a directory tree.

Returns

Returns 0 on failure, nonzero otherwise.

See also

rm


Methodsendfile

objectsendfile(array(string) headers, Filefrom, intoffset, intlen, array(string) trailers, Fileto)
objectsendfile(array(string) headers, Filefrom, intoffset, intlen, array(string) trailers, Fileto, 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()


Methodsimplify_path

stringsimplify_path(stringpath)

Description

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


Variablestderr

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()


Variablestdin

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); }


Variablestdout

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()


Methodwerror

voidwerror(strings)

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()


Typedefwrite_callback_t

local typedeffunction(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.


Methodwrite_file

intwrite_file(stringfilename, stringstr, int|voidaccess)

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

Annotations
@Pike.Annotations.Implements(Stream)
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


InheritStream

inherit Stream : Stream


Methodseek

intseek(intto, string|voidhow)


Methodtell

inttell()

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.FakeFilearg)

Description

Sizeof on a FakeFile returns the size of its contents.


Methodcast

(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.


Methodclose

intclose(void|stringdirection)

See also

Stdio.File()->close()


Methodcreate

Stdio.FakeFileStdio.FakeFile(stringdata, void|stringtype, void|intpointer)

See also

Stdio.File()->create()


Methoddup

this_programdup()

See also

Stdio.File()->dup()


Methoderrno

interrno()

Description

Always returns 0.

See also

Stdio.File()->errno()


Methodgetchar

intgetchar()

See also

Stdio.FILE()->getchar()


Methodgets

stringgets()

See also

Stdio.FILE()->gets()


Constantis_fake_file

constantint Stdio.FakeFile.is_fake_file

Description

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


Methodline_iterator

String.SplitIteratorline_iterator(int|voidtrim)

See also

Stdio.File()->line_iterator()


Methodpeek

int(-1..1)peek(int|float|voidtimeout)

See also

Stdio.File()->peek()


Methodquery_address

stringquery_address(void|boolis_local)

Description

Always returns 0.

See also

Stdio.File()->query_address()


Methodquery_close_callback

function(:void) query_close_callback()

See also

Stdio.File()->query_close_callback


Methodquery_id

mixedquery_id()

See also

Stdio.File()->query_id()


Methodquery_read_callback

function(:void) query_read_callback()

See also

Stdio.File()->query_read_callback


Methodquery_read_oob_callback

function(:void) query_read_oob_callback()

See also

Stdio.File()->query_read_oob_callback


Methodquery_write_callback

function(:void) query_write_callback()

See also

Stdio.File()->query_write_callback


Methodquery_write_oob_callback

function(:void) query_write_oob_callback()

See also

Stdio.File()->query_write_oob_callback


Methodread

stringread(void|int(0..)len, void|boolnot_all)

See also

Stdio.File()->read()


Methodread_function

function(:string) read_function(intnbytes)

See also

Stdio.File()->read_function()


Methodseek

intseek(intpos, string|voidhow)

See also

Stdio.File()->seek()


Methodset_blocking

voidset_blocking()

See also

Stdio.File()->set_blocking


Methodset_blocking_keep_callbacks

voidset_blocking_keep_callbacks()

See also

Stdio.File()->set_blocking_keep_callbacks


Methodset_close_callback

voidset_close_callback(function(:void) cb)

See also

Stdio.File()->set_close_callback


Methodset_id

voidset_id(mixed_id)

See also

Stdio.File()->set_id()


Methodset_nonblocking

voidset_nonblocking(function(:void) rcb, function(:void) wcb, function(:void) ccb, void|function(:void) rocb, void|function(:void) wocb)

See also

Stdio.File()->set_blocking


Methodset_nonblocking_keep_callbacks

voidset_nonblocking_keep_callbacks()

See also

Stdio.File()->set_blocking_keep_callbacks


Methodset_read_callback

voidset_read_callback(function(:void) cb)

See also

Stdio.File()->set_read_callback


Methodset_read_oob_callback

voidset_read_oob_callback(function(:void) cb)

See also

Stdio.File()->set_read_oob_callback


Methodset_write_callback

voidset_write_callback(function(:void) cb)

See also

Stdio.File()->set_write_callback


Methodset_write_oob_callback

voidset_write_oob_callback(function(:void) cb)

See also

Stdio.File()->set_write_oob_callback


Methodstat

Stdio.Statstat()

Description

Returns size and the creation time of the string.


Methodsync

int(1..1)sync()

Description

Always returns 1.

See also

Stdio.File()->sync()


Methodtell

inttell()

See also

Stdio.File()->tell()


Methodtruncate

booltruncate(intlength)

See also

Stdio.File()->truncate()


Methodunread

voidunread(strings)

See also

Stdio.FILE()->unread()


Methodwrite

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

See also

Stdio.File()->write()

Class Stdio.FakePipe

Description

This module emulates a bidirectional pipe/socket without using any actual file descriptors.


Methodcreate

Stdio.FakePipeStdio.FakePipe(void|stringdirection)


InheritInternalSocket

inherit InternalSocket : InternalSocket

Class Stdio.FakePipe.InternalSocket

Description

Class that implements one end of an emulated bi-directional pipe/socket.


Variable_other
Variable_read_buffer
Variable_write_buffer
Variablemux
Variablecond

protectedthis_program Stdio.FakePipe.InternalSocket._other
Stdio.Buffer Stdio.FakePipe.InternalSocket._read_buffer
Stdio.Buffer Stdio.FakePipe.InternalSocket._write_buffer
protectedThread.Mutex Stdio.FakePipe.InternalSocket.mux
protectedThread.Condition Stdio.FakePipe.InternalSocket.cond


Methodclose

intclose(string|voiddirection)


Methodcreate

Stdio.FakePipe.InternalSocketStdio.FakePipe.InternalSocket(this_program_other, Stdio.Buffer_read_buffer, Stdio.Buffer_write_buffer, Thread.Mutexmux, Thread.Conditioncond)


Methoderrno

interrno()


Methodget_close_callback

function(:void) get_close_callback()


Methodget_id

mixedget_id()


Methodget_read_callback

function(:void) get_read_callback()


Methodget_write_callback

function(:void) get_write_callback()


Methodis_open

boolis_open(string|voiddirection)


Variableother

this_program Stdio.FakePipe.InternalSocket.other

Description

The other end of the emulated pipe/socket.

Note

Read only


Methodpeek

int(-1..1)peek(int|float|voidtimeout, int|voidnot_eof)


Methodquery_backend

Pike.Backendquery_backend()


Methodread

string(8bit)read(int|voidnbytes, bool|voidnot_all)


Methodset_backend

voidset_backend(Pike.Backendbe)


Methodset_blocking

voidset_blocking()


Methodset_callbacks

voidset_callbacks(function(:void) rcb, function(:void) wcb, function(:void) ccb)


Methodset_close_callback

voidset_close_callback(function(:void) ccb)


Methodset_id

voidset_id(mixedid)


Methodset_nonblocking

voidset_nonblocking(function(:void) rcb, function(:void) wcb, function(:void) ccb)


Methodset_nonblocking_keep_callbacks

voidset_nonblocking_keep_callbacks()


Methodset_read_callback

voidset_read_callback(function(:void) rcb)


Methodset_write_callback

voidset_write_callback(function(:void) wcb)


Methodwrite

intwrite(sprintf_format|array(string(8bit)) data, sprintf_args ... args)

Class Stdio.NonblockingStream

Annotations
@Pike.Annotations.Implements(Stream)
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


InheritStream

inherit Stream : Stream


Methodset_blocking

voidset_blocking()


Methodset_read_callback
Methodset_write_callback
Methodset_close_callback
Methodset_fs_event_callback

NonblockingStreamset_read_callback(function(:void) f, mixed ... rest)
NonblockingStreamset_write_callback(function(:void) f, mixed ... rest)
NonblockingStreamset_close_callback(function(:void) f, mixed ... rest)
NonblockingStreamset_fs_event_callback(function(:void) f, intevent_mask, mixed ... rest)


Methodset_nonblocking

voidset_nonblocking(function(:void) a, function(:void) b, function(:void) c, function(:void)|voidd, function(:void)|voide)


Methodset_read_oob_callback
Methodset_write_oob_callback

optionalNonblockingStreamset_read_oob_callback(function(:void) f, mixed ... rest)
optionalNonblockingStreamset_write_oob_callback(function(:void) f, mixed ... rest)

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


Methodclose

voidclose()


Methodread

stringread(intnbytes)


Methodread_oob
Methodwrite_oob
Methodtcgetattr
Methodtcsetattr

optionalstringread_oob(intnbytes)
optionalintwrite_oob(stringdata)
optionalmapping(string:int) tcgetattr()
optionalinttcsetattr(mapping(string:int) attr, string|voidwhen)


Methodwrite

intwrite(stringdata)

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()


Methodcreate

Stdio.sendfileStdio.sendfile(array(string) headers, objectfrom, intoffset, intlen, array(string) trailers, objectto, 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()

Module Stdio.Pipe

Class Stdio.Pipe.Base

Description

This module provides a generic data processing non-blocking pipe interface. Set it to a pool of dedicated backends to use more than one CPU core (use one thread per backend). Use it in conjunction with the Shuffler to scale to an unlimited number of CPU cores.


Methodclose

finalintclose()


Methodcreate

Stdio.Pipe.BaseStdio.Pipe.Base(Gz.deflate|voidengine)

Description

Note that the Gz.deflate engine provided needs to be preconfigured using negative compression levels.


Variableengine

object Stdio.Pipe.Base.engine

Note

Read only


Methodprocess_data

protectedvoidprocess_data(string(8bit)data)


Methodprocess_header

protectedstring(8bit)process_header(string(8bit)data)


Methodprocess_init

protectedvoidprocess_init()


Methodprocess_trailer

protectedvoidprocess_trailer()


Methodset_backend

finalvoidset_backend(Pike.Backend_backend)


Methodset_close_callback

finalvoidset_close_callback(function(:void) ccb)


Methodset_nonblocking

finalvoidset_nonblocking(function(:void) rcb, function(:void) wcb, function(:void) ccb)


Methodset_read_callback

finalvoidset_read_callback(function(:void) rcb)


Methodset_write_callback

finalvoidset_write_callback(function(:void) wcb)


Methodwrite

finalintwrite(string(8bit)data)

Class Stdio.Pipe.Gunzip

Description

This module provides a gzip-uncompressing non-blocking pipe interface.


InheritBase

inherit .Base : Base

Class Stdio.Pipe.Gzip

Description

This module provides a gzip-compressing non-blocking pipe interface. Set it to a pool of dedicated backends to use more than one CPU core to compress data (use one thread per backend). Use it in conjunction with the Shuffler to scale to an unlimited number of CPU cores.


InheritBase

inherit .Base : Base