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 or provide 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 read

string read()
string read(int len)
string read(int len, int(0..1) 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() will not try its best to read as many bytes as you have asked for, but will merely return as much as the system read function will return. This 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() will only block if there's no data at all available.

If something goes wrong and not_all is set, zero will be 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() will fail and return zero, however.

If everything went fine, a call to errno() directly afterwards will return zero. That includes an end due to end-of-file or remote close.

If no arguments are given, read() will read to the end of the file or stream.

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


Method peek

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

Description

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

Returns 1 if there is data available to read, 0 (zero) if there is no data available, and -1 if something went wrong.

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.


Method read_oob

string read_oob()
string read_oob(int len)
string read_oob(int len, int(0..1) 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() will only return as many bytes of out-of-band data as are currently available.

If something goes wrong and not_all is set, zero will be 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() will fail and return zero, however.

If everything went fine, a call to errno() directly afterwards will return zero. That includes an end due to remote close.

If no arguments are given, read_oob() will read to the end of the stream.

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

Note

It is not guaranteed that all out-of-band data sent from the other end will be 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() 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() , write_oob()


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.

Writes data and returns the number of 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, or

  • nonblocking mode is used and not all data could be written without blocking.

-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() will fail and return -1.

If everything went fine, a call to errno() directly afterwards will return zero.

If data is an array of strings, they will be written sequence.

If more than one argument is given, sprintf() will be 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.

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 Locale.Charset.encoder .

See also

read() , write_oob()


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() will fail and return -1.

If everything went fine, a call to errno() directly afterwards will return zero.

If more than one argument is given, sprintf() will be used to format them.

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

Note

It is not guaranteed that all out-of-band data sent from the other end will be received. Most streams only allow for a single byte of out-of-band data at a time. Some streams will send the rest of the data as ordinary data.

See also

read_oob() , write()


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.

Note

This function is only available on some platforms.


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 will be closed. Otherwise only the directions specified will be 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.

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

open() , open_socket()


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 will be 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 will fail 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 will default to 00666, but note that on UNIX systems it's masked with the process umask before use.

See also

close()


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 sync

int(0..1) sync()

Description

Flush buffers to disk.

Returns

Returns 0 (zero) and sets errno on failure.

Returns 1 on success.


Method seek

int seek(int pos)
int seek(int unit, int mult)
int seek(int unit, int mult, int add)

Description

Seek to a specified offset in a file.

If mult or add are specified, pos will be calculated as pos  = unit *mult  + add .

If pos is negative it will be relative to the start of the file, otherwise it will be an absolute offset from the start of the file.

Returns

Returns the new offset, or -1 on failure.

Note

The arguments mult and add are considered obsolete, and should not be used.

See also

tell()


Method tell

int tell()

Description

Returns the current offset in the file.

See also

seek()


Method truncate

int(0..1) 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 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) will be 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()


Method errno

int errno()

Description

Return the errno for the latest failed file operation.


Method mode

int mode()

Description

Returns the open mode for the file.

0x1000

FILE_READ

0x2000

FILE_WRITE

0x4000

FILE_APPEND

0x8000

FILE_CREATE

0x0100

FILE_TRUNC

0x0200

FILE_EXCLUSIVE

0x0400

FILE_NONBLOCKING

0x0800

FILE_SET_CLOSE_ON_EXEC

0x0001

FILE_HAS_INTERNAL_REF

0x0002

FILE_NO_CLOSE_ON_DESTRUCT

0x0004

FILE_LOCK_FD

0x0010

FILE_NOT_OPENED


See also

open()


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


Method query_backend

Pike.Backend query_backend()

Description

Return the backend used for the callbacks.

See also

set_backend


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 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_close_on_exec

void set_close_on_exec(int(0..1) 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 is_open

int is_open()

Description

Returns true if the file is open.

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 query_fd

int query_fd()

Description

Returns the file descriptor number associated with this object.


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 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 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 pipe

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


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.

See also

assign() , dup()


Method dup

Stdio.Fd dup()


Method open_socket

int(0..1) open_socket(int|void port, string|void addr, int|void family)


Method set_keepalive

int(0..1) set_keepalive(int(0..1) on_off)


Method connect_unix

int(0..1) connect_unix(string filename)

Description

Open a UNIX domain socket 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.

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.


Method connect

int(0..1) connect(string dest_addr, int dest_port)
int(0..1) connect(string dest_addr, int dest_port, string src_addr, int src_port)

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.

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.


Method query_address

string query_address()
string query_address(int(0..1) 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 will be returned. Otherwise, if local is 1, the local end-point will be 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).

If this file is not a socket, is not connected, or some other error occurrs, 0 (zero) will be returned.

See also

connect()


Method `<<

Stdio.File `<<(string data)
Stdio.File `<<(mixed data)

Description

Write some data to a file.

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

Note

Throws an error if not all data could be written.

See also

write()


Method create

void Stdio.File(string filename)
void Stdio.File(string filename, string mode)
void Stdio.File(string filename, string mode, in access)
void Stdio.File(int fd)
void Stdio.File(int fd, string mode)

Description

See open() .

See also

open()


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 lock

Stdio.FileLockKey lock()
Stdio.FileLockKey lock(int(0..1) is_recursive)

Description

Makes an exclusive file lock on this file.

See also

trylock()


Method trylock

Stdio.FileLockKey trylock()
Stdio.FileLockKey trylock(int(0..1) is_recursive)

Description

Attempts to place a file lock on this file.

See also

lock()


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.

"rows" : int

Terminal rows.

"columns" : int

Terminal columns.

flag_name : int(0..1)

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(0..255)

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.


Inherit Fd_ref

inherit Fd_ref : Fd_ref


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.


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 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 open_socket

int open_socket(int|string|void port, string|void address, int|void family)

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

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. You may also specify an address to bind to if your machine has many IP numbers.

port can also be specified as a string, giving the name of the service associated with the port.

Finally, 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.

Returns

This function returns 1 for success, 0 otherwise.

See also

connect() , set_nonblocking() , set_blocking()


Method connect

int connect(string host, int|string port, void|string client, void|int|string client_port)

Description

This function connects a socket previously created with open_socket() to a remote socket through TCP/IP. 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 .

Returns

This function returns 1 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 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 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 async_connect

int async_connect(string host, int|string port, function(int: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 estabished, 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 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_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.

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() , PROP_IPC , PROP_NONBLOCK , PROP_SHUTDOWN , PROP_BUFFERED , PROP_REVERSE , PROP_BIDIRECTIONAL


Method create

void Stdio.File()
void Stdio.File(string filename)
void Stdio.File(string filename, string mode)
void Stdio.File(string filename, string mode, int mask)
void Stdio.File(string descriptorname)
void Stdio.File(int fd)
void 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 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 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 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 set_read_callback
Method set_write_callback
Method set_read_oob_callback
Method set_write_oob_callback
Method set_close_callback

void set_read_callback(function(mixed:int) read_cb)
void set_write_callback(function(mixed:int) write_cb)
void set_read_oob_callback(function(mixed:int) read_oob_cb)
void set_write_oob_callback(function(mixed:int) write_oob_cb)
void set_close_callback(function(mixed:int) close_cb)

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.

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

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

  • When the stream has been shut down, either due to an error or a close from the other end, close_cb will be called. errno will return the error that has occurred or zero in the case of a normal close. Note that close_cb will not be called for a local close, neither by a call to close or by destructing this object.

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.

Note

These functions do not set the file nonblocking.

Note

Callbacks are also set by 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.

See also

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


Method query_read_callback
Method query_write_callback
Method query_read_oob_callback
Method query_write_oob_callback
Method query_close_callback

function(mixed:int) query_read_callback()
function(mixed:int) query_write_callback()
function(mixed:int) query_read_oob_callback()
function(mixed:int) query_write_oob_callback()
function(mixed:int) query_close_callback()

Description

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

See also

set_nonblocking() , set_read_callback , set_write_callback , set_read_oob_callback , set_write_oob_callback , set_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 query_id

mixed query_id()

Description

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

See also

set_id()


Method set_nonblocking

void set_nonblocking(function(mixed:int) read_callback, function(mixed:int) write_callback, function(mixed:int) close_callback)
void set_nonblocking(function(mixed:int) read_callback, function(mixed:int) write_callback, function(mixed:int) close_callback, function(mixed: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_read_callback() , set_write_callback() , set_read_oob_callback() , set_write_oob_callback() , set_close_callback() set_nonblocking_keep_callbacks() , set_blocking_keep_callbacks()


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

  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.


Inherit file

inherit File : file


Method set_charset

void set_charset(string charset)

Description

Sets the input and output charset of this file to the specified charset .

The default charset is "ISO-8859-1".


Method gets

string gets()

Description

Read one line of input with support for input conversion.

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


Method ngets

array(string) ngets(void|int(1..) n)

Description

Get n lines.

Parameter n

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


Method pipe

File pipe(void|int flags)

Description

Same as Stdio.File()->pipe() .

Note

Returns an Stdio.File object, NOT a Stdio.FILE object.


Method write

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

Description

Write what with support for output_conversion.

See also

Stdio.File()->write()


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 _get_iterator

object _get_iterator()

Description

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

See also

line_iterator()


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.

See also

_get_iterator()


Method read

string read(int|void bytes, void|int(0..1) now)

Description

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

See also

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


Method ungets

void ungets(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() .

Note

The string must not contain line-feeds.

See also

read() , gets() , getchar()


Method getchar

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.

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


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 errno

int errno()

Description

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


Method listen_fd

int listen_fd(int fd, void|function accept_callback)

Description

This function does the same as port->bind, except that instead of creating a new socket and bind it to a port, it expects that the filedescriptor 'fd' is 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 bind

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

Description

Bind 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. Bind returns 1 on success, and zero on failiure.

If the optional argument 'ip' is given, bind will try to bind to this ip name or number.

See also

accept


Method bind_unix

int bind_unix(string path, void|function accept_callback)

Description

Bind opens a Unix domain socket at the filesystem location path. 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.

Returns

1 on success, and zero on failiure.

Note

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

See also

accept


Method close

void close()

Description

Closes the socket.


Method accept

Stdio.File accept()


Method query_address

string query_address(string arg1)

FIXME

Document this function.


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 query_backend

Pike.Backend query_backend()

Description

Return the backend used for the accept callback.

See also

set_backend


Inherit _port

inherit _port : _port


Method create

void Stdio.Port()
void Stdio.Port(int|string port)
void Stdio.Port(int|string port, function accept_callback)
void Stdio.Port(int|string port, function accept_callback, string ip)
void Stdio.Port("stdin")
void Stdio.Port("stdin", function 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 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

  CLASS Stdio.UDP

Description

UDP (User Datagram Protocol) handling.


Method close

int(0..1) close()

Description

Closes an open UDP port.

Note

This method was introduced in Pike 7.5.


Method bind

object bind(int|string port)
object bind(int|string port, string address)

Description

Binds a port for recieving or transmitting UDP.


Method enable_broadcast

int(0..1) 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 wait

int(0..1) wait(int|float timeout)

Description

Check for data and wait max. timeout seconds.

Returns

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


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


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 recepient 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_blocking

object set_blocking()

Description

Sets this object to be blocking.


Method connect

int(0..1) 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 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 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 query_backend

Pike.Backend query_backend()

Description

Return the backend used for the read callback.

See also

set_backend


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 set_type

object set_type(int sock_type)
object set_type(int sock_type, int family)

Description

Sets socket type and protocol family.


Method get_type

array(int) get_type()

Description

Returns socket type and protocol family.


Constant MSG_OOB

constant MSG_OOB

FIXME

Document this constant.


Constant MSG_PEEK

constant MSG_PEEK

FIXME

Document this constant.


Inherit UDP

inherit files.UDP : UDP


Method set_nonblocking

UDP set_nonblocking()
UDP set_nonblocking(function(mapping(string:int|string):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):) 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()

  Module Stdio.Terminfo


Method getTermcap

Termcap Stdio.Terminfo.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 Stdio.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 getTerm

Termcap Stdio.Terminfo.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 getFallbackTerm

Termcap Stdio.Terminfo.getFallbackTerm(string term)

Description

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

See also

Stdio.Terminfo.getTerm


Method is_tty

int Stdio.Terminfo.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.Termcap

Description

Termcap terminal description object.


Inherit TermMachine

inherit TermMachine : TermMachine


Variable aliases

array(string) aliases


Method tputs

string tputs(string s)

Description

Put termcap string


Method create

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

  CLASS Stdio.Terminfo.Terminfo

Description

Terminfo terminal description object


Inherit TermMachine

inherit TermMachine : TermMachine


Variable aliases

array(string) aliases


Method tputs

string tputs(string s)

FIXME

Document this function


Method create

void Stdio.Terminfo.Terminfo(string filename)

  CLASS Stdio.Readline


Method get_output_controller

OutputController get_output_controller()

Description

get current output control object

Returns

Terminal output controller object


Method get_input_controller

InputController get_input_controller()

Description

get current input control object

Returns

Terminal input controller object


Method get_prompt

string get_prompt()

Description

Return the current prompt string.


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 set_echo

void set_echo(int onoff)

Description

Set text echo on or off.

Parameter onoff

1 for echo, 0 for no echo.


Method gettext

string gettext()

FIXME

Document this function


Method getcursorpos

int getcursorpos()

FIXME

Document this function


Method setcursorpos

int setcursorpos(int p)

FIXME

Document this function


Method setmark

int setmark(int p)

FIXME

Document this function


Method getmark

int getmark()

FIXME

Document this function


Method insert

void insert(string s, int p)

FIXME

Document this function


Method delete

void delete(int p1, int p2)

FIXME

Document this function


Method pointmark

array(int) pointmark()

FIXME

Document this function


Method region

string region(int ... args)

FIXME

Document this function


Method kill

void kill(int p1, int p2)

FIXME

Document this function


Method add_to_kill_ring

void add_to_kill_ring(string s)

FIXME

Document this function


Method kill_ring_yank

string kill_ring_yank()

FIXME

Document this function


Method history

void history(int n)

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 redisplay

void redisplay(int clear, int|void nobackup)

FIXME

Document this function


Method newline

string newline()

FIXME

Document this function


Method eof

void eof()

FIXME

Document this function


Method message

void message(string msg)

Description

Print a message to the output device


Method write

void write(string msg, void|int word_wrap)

FIXME

Document this function


Method list_completions

void list_completions(array(string) c)

FIXME

Document this function


Method set_nonblocking

void set_nonblocking(function f)

FIXME

Document this function


Method set_blocking

void set_blocking()

FIXME

Document this function


Method edit

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

FIXME

Document this function


Method read

string read(string|void 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 get_history

History get_history()

FIXME

Document this function


Method create

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

  CLASS Stdio.Readline.OutputController

FIXME

Ought to have support for charset conversion.


Method turn_on

void turn_on(string ... atts)

Description

Set the provided attributes to on.


Method turn_off

void turn_off(string ... atts)

Description

Set the provided attributes to off.


Method disable

void disable()


Method enable

void enable()


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 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_write

void low_write(string s, void|int word_break)


Method write

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


Method low_move_downward

void low_move_downward(int n)


Method low_move_upward

void low_move_upward(int n)


Method low_move_forward

void low_move_forward(int n)


Method low_move_backward

void low_move_backward(int n)


Method low_erase

void low_erase(int n)


Method move_forward

void move_forward(string s)


Method move_backward

void move_backward(string s)


Method erase

void erase(string s)


Method newline

void newline()


Method bol

void bol()


Method clear

void clear(int|void partial)


Method beep

void beep()


Method create

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

  CLASS Stdio.Readline.InputController

FIXME

Ought to have support for charset conversion.


Method isenabled

int isenabled()


Method enable

int enable(int ... e)


Method disable

int disable()


Method run_blocking

int run_blocking()


Method set_close_callback

void set_close_callback(function(:int) ccb)


Method nullbindings

void nullbindings()

Description

Clears the bindings.


Method grabnextkey

void grabnextkey(function g)


Method bindstr

function bindstr(string str, function f)


Method unbindstr

function unbindstr(string str)


Method getbindingstr

function getbindingstr(string str)


Method bindtc

function bindtc(string cap, function f)


Method unbindtc

function unbindtc(string cap)


Method getbindingtc

function getbindingtc(string cap)


Method parsekey

string parsekey(string k)


Method bind

function bind(string k, function f)


Method unbind

function unbind(string k)


Method getbinding

function getbinding(string k, string cap)


Method getbindings

mapping(string:function) getbindings()


Method create

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

  CLASS Stdio.Readline.DefaultEditKeys


Method self_insert_command

void self_insert_command(string str)


Method quoted_insert

void quoted_insert()


Method newline

void newline()


Method up_history

void up_history()


Method down_history

void down_history()


Method backward_delete_char

void backward_delete_char()


Method delete_char_or_eof

void delete_char_or_eof()


Method forward_char

void forward_char()


Method backward_char

void backward_char()


Method beginning_of_line

void beginning_of_line()


Method end_of_line

void end_of_line()


Method transpose_chars

void transpose_chars()


Method capitalize_word

void capitalize_word()


Method upcase_word

void upcase_word()


Method downcase_word

void downcase_word()


Method forward_word

void forward_word()


Method backward_word

void backward_word()


Method kill_word

void kill_word()


Method backward_kill_word

void backward_kill_word()


Method kill_line

void kill_line()


Method kill_whole_line

void kill_whole_line()


Method yank

void yank()


Method kill_ring_save

void kill_ring_save()


Method kill_region

void kill_region()


Method set_mark

void set_mark()


Method swap_mark_and_point

void swap_mark_and_point()


Method redisplay

void redisplay()


Method clear_screen

void clear_screen()


Method set_default_bindings

void set_default_bindings()


Method create

void Stdio.Readline.DefaultEditKeys(object readline)

  CLASS Stdio.Readline.History


Method encode

string encode()


Method get_history_num

int get_history_num()


Method history

string history(int n, string text)


Method initline

void initline()


Method finishline

void finishline(string text)


Method set_max_history

void set_max_history(int maxhist)


Method create

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

  Module Stdio


Method get_all_active_fd

array(int) Stdio.get_all_active_fd()

Description

Returns the id of all the active file descriptors.


Method notify

void Stdio.notify(void|int notification, function(void:void) callback)

Description

Receive notification when change occur within the fd. To use, create a Stdio.File object of a directory like Stdio.File(".") and then call notify() with the appropriate parameters.

Note

When a program registers for some notification, only the first notification will be received unless DN_MULTISHOT is specified as part of the notification argument.

Note

At present, this function is Linux-specific and requires a kernel which supports the F_NOTIFY fcntl() call.

Parameter notification

What to notify the callback of. See the Stdio.DN_* constants for more information about possible notifications.

Parameter callback

Function which should be called when notification is received. The function gets the signal used to indicate the notification as its argument and shouldn't return anyting.


Constant PROP_BIDIRECTIONAL

constant Stdio.PROP_BIDIRECTIONAL

FIXME

Document this constant.


Constant PROP_BUFFERED

constant Stdio.PROP_BUFFERED

FIXME

Document this constant.


Constant PROP_SHUTDOWN

constant Stdio.PROP_SHUTDOWN

FIXME

Document this constant.


Constant PROP_NONBLOCK

constant Stdio.PROP_NONBLOCK

FIXME

Document this constant.


Constant PROP_REVERSE

constant Stdio.PROP_REVERSE

FIXME

Document this constant.


Constant PROP_IPC

constant Stdio.PROP_IPC

FIXME

Document this constant.


Constant IPPROTO

constant Stdio.IPPROTO

FIXME

Document this constant.


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.


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.


Method _sprintf

string Stdio._sprintf(int type, void|mapping flags)


Constant DN_ACCESS

constant Stdio.DN_ACCESS

Description

Used in File.notify() to get a callback when files within a directory are accessed.


Constant DN_MODIFY

constant Stdio.DN_MODIFY

Description

Used in File.notify() to get a callback when files within a directory are modified.


Constant DN_CREATE

constant Stdio.DN_CREATE

Description

Used in File.notify() to get a callback when new files are created within a directory.


Constant DN_DELETE

constant Stdio.DN_DELETE

Description

Used in File.notify() to get a callback when files are deleted within a directory.


Constant DN_RENAME

constant Stdio.DN_RENAME

Description

Used in File.notify() to get a callback when files within a directory are renamed.


Constant DN_ATTRIB

constant Stdio.DN_ATTRIB

Description

Used in File.notify() to get a callback when attributes of files within a directory are changed.


Constant DN_MULTISHOT

constant Stdio.DN_MULTISHOT

Description

Used in File.notify() . If DN_MULTISHOT is used, signals will be sent for all notifications the program has registred for. Otherwise only the first event the program is listening for will be received and then the program must reregister for the events to receive futher events.


Inherit files

inherit files : files


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


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


Method read_file

string Stdio.read_file(string filename)
string Stdio.read_file(string filename, int start, int len)

Description

Read len lines from a 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.

See also

read_bytes() , write_file()


Method read_bytes

string Stdio.read_bytes(string filename, int start, int len)
string Stdio.read_bytes(string filename, int start)
string Stdio.read_bytes(string filename)

Description

Read len number of bytes from the 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 if filename isn't a regular file.

Returns

Returns 0 (zero) on failure to open filename .

Returns a string with the requested data otherwise.

See also

read_file , write_file() , append_file()


Method write_file

int Stdio.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.

See also

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


Method append_file

int Stdio.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.

See also

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


Method file_size

int Stdio.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.

See also

file_stat() , write_file() , read_bytes()


Method append_path

string Stdio.append_path(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).

Note

Warning: This does not work on NT. (Consider paths like: k:/fnord)

See also

combine_path()


Method simplify_path

string Stdio.simplify_path(string path)

Description

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


Method perror

void Stdio.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 is_file

int Stdio.is_file(string path)

Description

Check if a path is a file.

Returns

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

See also

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


Method is_dir

int Stdio.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_link

int Stdio.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 exist

int Stdio.exist(string path)

Description

Check if a path exists.

Returns

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

See also

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


Method cp

int Stdio.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 65536 bytes.


Method file_equal

int Stdio.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 async_cp

void Stdio.async_cp(string from, string to, function(int: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 mkdirhier

int Stdio.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 recursive_rm

int Stdio.recursive_rm(string path)

Description

Remove a file or directory a directory tree.

Returns

Returns 0 on failure, nonzero otherwise.

See also

rm


Method sendfile

object Stdio.sendfile(array(string) headers, File from, int offset, int len, array(string) trailers, File to)
object Stdio.sendfile(array(string) headers, File from, int offset, int len, array(string) trailers, File to, function(int: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 before or 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.

Bugs

FIXME: Support for timeouts?

See also

Stdio.File->set_nonblocking()


Method werror

void Stdio.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()

  CLASS Stdio.Fd_ref

Description

Proxy class that contains stub functions that call the corresponding functions in Fd .

Used by File .


Variable _fd

Fd _fd

Description

Object to which called functions are relayed.

  CLASS Stdio.Fd

Description

Low level I/O operations. Use File instead.

  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.

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 create

void 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.FakeFile

Description

A string wrapper that pretends to be a Stdio.File object.


Constant is_fake_file

constant is_fake_file

Description

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


Method close

int close(void|string direction)

See also

Stdio.File()->close()


Method create

void 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 line_iterator

String.SplitIterator line_iterator(int|void trim)

See also

Stdio.File()->line_iterator()


Method query_id

mixed query_id()

See also

Stdio.File()->query_id()


Method set_id

void set_id(mixed _id)

See also

Stdio.File()->set_id()


Method read_function

function(:string) read_function(int nbytes)

See also

Stdio.File()->read_function()


Method peek

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

See also

Stdio.File()->peek()


Method query_address

string query_address(void|int(0..1) is_local)

Description

Always returns 0.

See also

Stdio.File()->query_address()


Method read

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

See also

Stdio.File()->read()


Method seek

int seek(int pos, void|int mult, void|int add)

See also

Stdio.File()->seek()


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

int(0..1) truncate(int length)

See also

Stdio.File()->truncate()


Method write

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

See also

Stdio.File()->write()


Method cast

mixed cast(string to)

Description

A FakeFile can be casted to a string.


Method _sizeof

int(0..) _sizeof()

Description

Sizeof on a FakeFile returns the size of its contents.

  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.

See also

NonblockingStream , BlockFile , File , FILE

  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

  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