include "bufio.m"; Iobuf: import Bufio; bufio:= load Bufio Bufio->PATH; OREAD: con Sys->OREAD; OWRITE: con Sys->OWRITE; ORDWR: con Sys->ORDWR; EOF: con -1; ERROR: con -2; Iobuf: adt { seek: fn(b: self ref Iobuf, n, where: int) : int; read: fn(b: self ref Iobuf, a: array of byte, n: int): int; write: fn(b: self ref Iobuf, a: array of byte, n: int): int; getb: fn(b: self ref Iobuf) : int; getc: fn(b: self ref Iobuf) : int; gets: fn(b: self ref Iobuf, sep: int) : string; gett: fn(b: self ref Iobuf, sep: string) : string; putb: fn(b: self ref Iobuf, b: byte) : int; putc: fn(b: self ref Iobuf, c: int) : int; puts: fn(b: self ref Iobuf, s: string) : int; flush: fn(b: self ref Iobuf): int; close: fn(b: self ref Iobuf); }; open: fn(name: string, mode: int) : ref Iobuf; create: fn(name: string, mode, perm: int) : ref Iobuf; fopen: fn(fd: ref Sys->FD, mode: int) : ref Iobuf; flush: fn();
The Bufio module keeps an internal reference to files opened for writing so that they can be flushed before being garbage collected. Flushing all dirty files is done with an explicit call to bufio->flush(), usually just before exiting the program.
getb ( )
Read a single byte from the buffered stream and return its value as an int. getc ( )
Read a single Unicode character, encoded in UTF (see utf), and return its value as an int.
gets (sepchar)
Read a line, up to and including a character specified by sepchar, typically a newline. If none is found, read to the end of the file. The returned string includes the terminating character. gett (sepstr)
Read characters until one of the characters in sepstr. The returned string includes the separator. If none of the separator characters is found, read to the end of the file. putb (b), putc (c), and puts (s)
Each writes its argument, a byte, a character, or a string, respectively. Text is encoded in UTF. flush ( )
Write contents of the write buffer to the file. Meaningful only for files opened for writing; has no effect on files opened for reading. close ( )
Flush remaining data in the buffer, if necessary, close the associated file, and discard buffers associated with the file. After close, no further function calls are allowed on the iobuf adt. Diagnostics
Calls that return a ref type (open, fopen, gets, and gett) return nil when encountering end of file or errors. When an error occurs, the error string, printable with the %r format, will usually be set as a consequence of an error in the underlying Sys module. The other functions return Bufio->EOF upon encountering end of file, and Bufio->ERROR when encountering other errors. Example
The code fragment
lc:= bufio->open("/net/tcp/0/local", bufio->OREAD); addr:= lc.gets('\n'); lc = nil;
opens the file /net/tcp/0/local and reads a line (including the terminating newline character) from this file to initialize the string variable addr. The file is closed implicitly by discarding (assigning nil to) the only reference to its Iobuf.