iofile (lib)

See also: list.type


The iofile library contains functions and behaviors for synchronous local file operations.

Library Functions

open( fileName   mode ) → file, error

Opens a file in one of the following modes: #r for reading, #w for writing, #a for appending.

new f ='/etc/motd', #r)
print( f:read() )
Have a lot of fun...

File Object Behaviors

:bufferMode( mode   [size] )

Sets the I/O buffering mode for the file, which can be either #none for no buffering, #full for full buffering, or #line for line-based buffering. The optional size parameter sets the buffer size.

:close( ) → result

Closes an open file.

new f ='/etc/motd', #r)
print( f:close() )

A useful idiom to check for errors is

new f = assert( mode))

If the open fails, the error message goes as the second argument to assert, which then shows the message.

:each( ƒ⇠line,count ) → file

Reads the file line by line, calling ƒ on each line of text. ƒ can also receive the current line number using the count parameter.

new f ='/etc/motd', #r)
f:each{ lc | print(#line lc) }
line Have a lot of fun...

:lines( ) → list

Reads the file line by line, returning a list of lines.

(: "Have a lot of fun..." )

:read( opt1   [opt2...] ) → result, error

Reads from the file according to the mode set in opt1, which can be either of the following: #number reads a number, #line reads a line, #eol reads a line and returns it including the end-of-line character, #all reads the entire file. If instead of an option string a number is passed, that amount of bytes will be read and returned.

new f ='/etc/motd', #r)
print( f:read() )
Have a lot of fun...

:status( ) → info

Returns the status of the file, which can be either nil for undefined states, #open for open files, or #closed for closed files.

new f ='/etc/motd', #r)
print( f:status() )

:seek( base   position ) → position

Moves the current position within the file, relative to the base, which can be either #set for the absolute position, #current for the current position, or #end counted from the end.

new f ='/etc/motd', #r)
f:seek(#set 3)
print( f:read() )
e a lot of fun...