std.fs

index · std

Overview

File system operations for reading, writing, and manipulating files and directories. Wraps low-level std.core functions with higher-level conveniences like recursive mkdir and file listing.

Functions

NameSignature
symlinksymlink(src, dst) -> ok, err
chmodchmod(path, mode) -> ok, err
cwdcwd() -> path
chdirchdir(path) -> ok, err
statstat(path) -> info, err
fstatfstat(fd) -> info, err
open_readopen_read(path) -> fd, err
open_privateopen_private(path) -> fd, err
flockflock(fd, how) -> ok, err
locklock(path, how) -> fd, err
syncsync(target) -> ok, err
sync_dirsync_dir(path) -> ok, err
replacereplace(path, text, mode) -> ok, err
closeclose(fd) -> ok, err
preadpread(fd, count, offset) -> data, err
realpathrealpath(path) -> path, err
readlinkreadlink(pathname) -> target, err
split_path_by_dirsplit_path_by_dir(pathname) -> dirs
mkdirmkdir(pathname, mode, recursive) -> ok, err
list_dirlist_dir(path) -> entries, err
list_numberedlist_numbered(path, pattern) -> names
fast_list_dirfast_list_dir(path) -> entries, err
empty_dirempty_dir(path) -> is_empty, err
non_empty_dirnon_empty_dir(path) -> is_non_empty, err
removeremove(path, recursive) -> ok, err
renamerename(src, dst) -> ok, err
list_fileslist_files(dir, pattern, mode, resolve_links) -> files, err
dir_existsdir_exists(filename) -> exists
file_existsfile_exists(filename, mode) -> exists
read_fileread_file(filename) -> content, err
write_filewrite_file(filename, text) -> ok, err
statvfsstatvfs(path) -> info, err
fdopenfdopen(fd, mode) -> file, err

symlink(src, dst) -> ok, err

Create a symbolic link

Creates a symbolic link at dst pointing to src. The argument order matches ln -s src dst. Returns nil and an error string on failure.

chmod(path, mode) -> ok, err

Change file mode bits

Changes the permission bits of the file at path. Mode is an octal string (e.g. "0755"). Returns nil and an error string on failure.

cwd() -> path

Get the current working directory

Returns the absolute path of the process's current working directory. Wraps getcwd(2). Returns an empty string if the path cannot be determined.

chdir(path) -> ok, err

Change the current working directory

Changes the process's current working directory to path. Returns true on success, or nil and an error string on failure (e.g., path does not exist or permission denied).

stat(path) -> info, err

Get file or directory status information

Returns a table with fields: mode (file type character), size, perms, uid, gid, atime, mtime, ctime, dev, ino. Returns nil and error on failure.

fstat(fd) -> info, err

Get the status of an open file descriptor

Returns the table stat gives, for the file fd holds open. Wraps fstat(2). A check by path cannot vouch for the file a later open returns; a check of the open fd can.

open_read(path) -> fd, err

Open a file to read, without blocking

Opens path read-only, close-on-exec and non-blocking, and returns the raw fd. A FIFO opens at once instead of waiting for a writer. Check the fd with fstat before a read, and close it with close.

open_private(path) -> fd, err

Create a new file only its owner can read

Creates path write-only and close-on-exec, and returns the raw fd. The file is born with mode 0600, so no other user can open it in the gap a later chmod would leave. The umask can only narrow that mode.

An existing path is refused with "File exists", and so is a symlink, even one to a missing file. Wrap the fd with fdopen(fd, "w") to get a FILE*, or close it with close. A file that must outlast a power loss is synced, and so is its directory: sync shows the steps.

flock(fd, how) -> ok, err

Take, convert or drop an advisory lock on an open fd

Wraps flock(2), and never blocks. how is "ex" for an exclusive lock, "sh" for a shared one, or "un" to drop it. Another word raises.

Answers true, or nil and "locked" when another holder is in the way. A failure answers nil and the errno text, which is never "locked".

The lock belongs to the open file description, not to the fd number or the process. A dup of the fd shares it, and so does a child of fork. Another open of the same file is another taker, even in the same process. The lock drops when the last fd on that description closes, so a killed process frees it.

Converting between "sh" and "ex" is not atomic. The kernel drops the old lock first, so a refused conversion leaves the fd holding none.

lock(path, how) -> fd, err

Lock a path for as long as the answered fd stays open

Opens path and takes flock(fd, how) on it, without blocking. path is a directory or a file; a missing file is created, mode 0600. The fd is close-on-exec, so a program run by exec does not keep the lock.

Answers the raw fd, which holds the lock until close or until the process ends. A refusal answers nil and "locked"; a failure answers nil and the errno text. flock converts or drops the lock on the answered fd.

local fd, err = std.fs.lock(data_dir, "ex")
if not fd and err == "locked" then
	-- another process holds the directory
end

Never lock a .mneme store file itself. MNEME's write transaction takes a blocking flock on its own fd, and would wait for this lock forever. Lock the store's directory, or a file beside it.

sync(target) -> ok, err

Hand a file's bytes to the disk

Wraps fsync(2). target is a raw fd, or a FILE* from io.open or fdopen, whose buffer is flushed first. Answers true, or nil and the errno text. A closed FILE*, or any other value, raises.

When it answers true, the kernel has handed the file's data and its metadata, the size and the mode among them, to the device, and asked the device to flush its write cache. A crash of the process or the machine after that keeps the bytes.

It does not make the file's name last. A file made or renamed since its directory was last synced can still be gone after a power loss: follow with sync_dir. A key made in place, with no rename, goes so:

local fd = assert(std.fs.open_private(path))
local f = assert(std.fs.fdopen(fd, "w"))
assert(f:write(key))
assert(std.fs.sync(f))
assert(f:close())
assert(std.fs.sync_dir(dir))

What is not promised: a device that answers a cache flush before it writes can still lose the bytes. A failed sync, "Input/output error" above all, may leave pages the kernel has already dropped, and a second sync can answer true over bytes that never reached the disk. Write the file again from its source instead.

sync_dir(path) -> ok, err

Make the entries of a directory last

Opens the directory path and syncs it, as sync does a file. A file made, renamed or removed in it then keeps its name past a power loss. Answers true, or nil and the errno text: "Not a directory" for any other kind of file.

replace(path, text, mode) -> ok, err

Put a file's new bytes in place in one step

Writes text to a new file beside path, syncs it and renames it over path, then syncs the directory. The new file is born 0600, and mode, an octal string such as "0644", is set on it before the sync. A text that is not a string, or a mode of any other shape, raises, and nothing is written.

A reader of path sees the old file or the new one, never part of either. Answers true once the directory is synced: the new file then survives a power loss as well as a crash.

A refusal answers nil and the errno text. Before the rename, a refusal removes the new file, and the old one stays whole. A refused sync_dir after the rename answers nil too, though the new file is already in place: its name may not survive a power loss.

The new file is .<name>.<hex>.tmp in the same directory, made with open_private, so no other user can read it, and a link planted at that name is refused. A path that is a symlink is replaced by the file, and its target is left alone. Two calls on one path at once each write their own file, and the last rename wins.

replace does not suit a file that must be made only once, such as a key two processes may race to create: the second rename would put its key over the first. Make that file with open_private and sync it.

close(fd) -> ok, err

Close a raw file descriptor

pread(fd, count, offset) -> data, err

Read from a file descriptor at an offset

Reads up to count bytes at offset, 0 by default, and leaves the fd's position alone. Wraps pread(2): it reads until count or the end of the file, and retries on EINTR. A read past the end gives a short or empty string, not an error.

realpath(path) -> path, err

Resolve a path to its canonical form

Returns the absolute path with every symlink, . and .. resolved. Wraps realpath(3). Every component must exist. A relative path resolves against the working directory. A loop of links fails.

readlink(pathname) -> target, err

Read the target of a symbolic link

Returns the raw link target exactly as stored (does not resolve further symlinks or relative paths). Wraps readlink(2). Returns nil and an error string if path is not a symlink or cannot be read.

The magic links of /proc read whole: /proc/self/exe gives the running binary's path, and a /proc/<pid>/fd/<n> link its full target.

split_path_by_dir(pathname) -> dirs

Split a pathname into an array of directory components

Splits a pathname on / separators and returns the components as an ordered array. Leading slashes are discarded; the final component is included even if it names a file rather than a directory.

Example: split_path_by_dir("/usr/local/bin") → {"usr","local","bin"}

mkdir(pathname, mode, recursive) -> ok, err

Create a directory, optionally with parent directories

mode is an octal permission string passed to mkdir(2), e.g. "0755". Defaults to "0755" (subject to umask) when omitted. When recursive is true, any missing parent directories are created in order, each with the same mode. Returns nil and an error string if creation fails at any step.

With recursive, a segment that already stands must be a directory or a link to one. A plain file or a dangling link answers nil and "File exists", as the call without recursive does over a file.

list_dir(path) -> entries, err

List all entries in a directory

Returns an array of filenames for every entry in path, including "." and "..". The array is unordered. Returns nil and an error string if the path does not exist or is not a directory.

list_numbered(path, pattern) -> names

List the entries a pattern numbers, in number order

The names under path that pattern captures a number from, sorted by that number, so event2 comes before event10 where the names alone would not. A path that does not read gives an empty table.

fast_list_dir(path) -> entries, err

List directory entries using optimized syscall

Same return shape as list_dir (array of filenames including "." and ".."), but uses the getdents64 syscall directly, avoiding per-entry stat calls. Faster than list_dir for large directories. Returns nil and an error string on failure.

empty_dir(path) -> is_empty, err

Check if a directory is empty

Returns true if the directory exists and contains no entries (only "." and ".." entries). Returns nil and an error message if the path doesn't exist or isn't a directory.

non_empty_dir(path) -> is_non_empty, err

Check if a directory is non-empty

Returns true if the directory exists and contains entries beyond "." and "..". Returns nil and an error message if the path doesn't exist or isn't a directory.

remove(path, recursive) -> ok, err

Remove a file or directory

Removes a file or directory. If recursive is true and the path is a directory, all contents are removed recursively. Returns nil and an error if the path doesn't exist or cannot be removed.

rename(src, dst) -> ok, err

Rename or move a file or directory

Renames or moves a file or directory from src to dst. If dst is an existing directory, src is moved inside it. Returns an error on failure.

list_files(dir, pattern, mode, resolve_links) -> files, err

List files in a directory matching a pattern and mode

Returns a table keyed by filename, with each value containing mode, size, perms, uid, gid, atime, and optionally target fields. Default pattern is ^.*, default mode is "f".

dir_exists(filename) -> exists

Check if a directory exists at the given path

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

file_exists(filename, mode) -> exists

Check if a file exists and matches the given mode

Returns true if the path exists and matches the given mode (e.g., "f" for regular file, "d" for directory, "l" for symlink). Defaults to "f".

read_file(filename) -> content, err

Read the entire contents of a file

Reads the file at the given path and returns its contents as a string. Returns nil and an error message if the file cannot be read.

write_file(filename, text) -> ok, err

Write text content to a file

Opens path for writing (mode "w+"), which creates the file if it does not exist and truncates it if it does. Writes text and closes the file. Returns true on success, or nil and an error string on failure.

It does not sync. A crash or a power loss can leave the file empty or short, with the old bytes already gone. A file whose loss costs more than a rewrite goes through replace.

statvfs(path) -> info, err

Get filesystem capacity information for a path

Wraps statvfs(3). Returns a table with bsize, blocks, bfree, bavail, files and ffree. Block counts are in units of bsize, which carries the fragment size (f_frsize) the counts are defined in, so blocks * bsize is byte-correct. bavail is the space available to unprivileged users; bfree includes the root reserve.

fdopen(fd, mode) -> file, err

Convert a raw file descriptor to a Lua FILE* object

Transforms a raw file descriptor into a Lua FILE* object. Mode: "r" for read, "w" for write, "a" for append. The original fd is closed; the FILE* owns a duplicate descriptor.