fs
import fs from "fs";
import io from "io";
fs.write_file("notes.txt", "first line\n") or { return 1; };
fs.append_file("notes.txt", "second line\n") or { return 1; };
let text: string = fs.read_file("notes.txt") or {
io.eprintln("cannot read notes.txt: {err}");
return 1;
};fs works on the real file system. Paths are []const u8 in the
platform’s syntax; / works as a separator everywhere, \ on Windows too.
To build paths, use path: path.join(dir, "notes.txt"). Every
failure is an io.IoError.
Whole files
| Function | Does |
|---|---|
read_file(path) -> string or io.IoError | The file’s bytes as a string |
write_file(path, data) -> void or io.IoError | Create or replace the file |
append_file(path, data) -> void or io.IoError | Create the file or add to its end |
copy_file(src, dst) -> void or io.IoError | Copy the bytes, replacing dst |
Opening a file
For more control, open a File. Say what you want to do with it
(Access) and what should happen if it does or doesn’t exist
(Creation):
var f: fs.File = fs.open("data.bin", fs.Access.ReadWrite, fs.Creation.OpenOrCreate) or { return 1; };
defer f.close();
f.seek(16, fs.Whence.Start) or { return 1; };
var buf: [4]u8;
let n: i64 = f.read(buf[0..4]) or { return 1; };Access | |
|---|---|
Read | read only |
Write | write only |
ReadWrite | both |
Append | write, always at the end |
Creation | If the file exists | If it doesn’t |
|---|---|---|
Existing | open it | NotFound |
OpenOrCreate | open it, keep its contents | create it |
CreateNew | AlreadyExists | create it |
Truncate | open it and empty it | create it |
Any Creation other than Existing needs a writing access, whether or
not the file exists: open(p, Access.Read, Creation.Truncate) is
InvalidInput. Opening a directory is IsADirectory.
| Method | Does |
|---|---|
f.read(buf) -> i64 or io.IoError | Read up to buf.len bytes; 0 at the end |
f.write(data) -> i64 or io.IoError | Write some of data at the position |
f.seek(off, whence) -> i64 or io.IoError | Move to off from Start, Current or End; returns the new position |
f.metadata() -> Metadata or io.IoError | Size, kind, modification time |
f.reader() -> io.Reader, f.writer() -> io.Writer | The file as a stream (for write_all, BufWriter, read_line) |
f.close() | Close it; closing twice does nothing |
A File doesn’t close itself: close every file you open, defer f.close(); is the easy way. After close the other methods return
InvalidInput.
Length, sync and locks
| Method | Does |
|---|---|
f.truncate(size) -> void or io.IoError | Set the length: shorter drops the end, longer adds zero bytes; the position stays |
f.sync() -> void or io.IoError | Return once what was written is on the disk |
f.lock(kind: Lock) -> void or io.IoError | Lock the whole file, waiting while someone else holds a conflicting lock |
f.try_lock(kind: Lock) -> bool or io.IoError | The same without waiting: false when someone else holds it |
f.unlock() -> void or io.IoError | Release the lock (close does too) |
Lock.Shared holders can share the file; a Lock.Exclusive holder is
alone. A lock belongs to the File, not the program: two Files of the
same path conflict, so one process can’t take a lock another one holds,
and neither can a second File of your own. Locking again replaces your
earlier lock.
var f: fs.File = fs.open("app.lock", fs.Access.ReadWrite, fs.Creation.OpenOrCreate) or { return 1; };
defer f.close();
let mine: bool = f.try_lock(fs.Lock.Exclusive) or { return 1; };
if (!mine) {
io.eprintln("another copy is already running");
return 1;
}On Linux and macOS locks are advisory: they only stop others who lock
too. On Windows they are enforced: while a File holds an exclusive lock,
other Files can’t read or write the file, and under a shared one nobody
writes it. A File opened Append can’t be locked or truncated on
Windows.
Streams make files and buffering work together:
var f: fs.File = fs.open("big.txt", fs.Access.Write, fs.Creation.Truncate) or { return 1; };
var out: io.BufWriter = io.buf_writer(f.writer());
for (i in 0..100000) { out.write_all("row {i}\n") or { return 1; }; }
out.close() or { return 1; };
f.close();Directories and paths
| Function | Does |
|---|---|
exists(path) -> bool | Is there something at path (following links)? |
metadata(path) -> Metadata or io.IoError | What is there (following links) |
link_metadata(path) -> Metadata or io.IoError | What is there, not following a link at the end of path (a link is Symlink) |
mkdir(path, mode = 0o777) | Create one directory; its parent must exist. mode is its permission bits, less the umask (0o700: only you may enter it); not used on Windows |
mkdir_all(path) | Create a directory and any missing parents; fine if it exists |
remove(path) | Remove a file, a link, or an empty directory |
remove_all(path) | Remove a directory and everything in it (never following links) |
rename(src, dst) | Move within a volume, replacing a file at dst |
read_dir(path) -> DirIter or io.IoError | The entries of a directory |
temp_dir() -> string | A directory for temporary files |
var it: fs.DirIter = fs.read_dir("assets") or { return 1; };
for (e in it) {
if (e.kind == fs.FileKind.Dir) {
io.println("{e.name}/");
} else {
io.println(e.name);
}
}read_dir yields a DirEntry { name: string; kind: FileKind; } for each
entry except . and .., in no particular order. name is the entry’s
name, not a path: path.join(dir, e.name) makes one. The listing closes
itself after the last entry; if you stop early, call it.close().
temp_dir() is $TMPDIR, $TMP or $TEMP (the first one set), or
/tmp.
Walking a tree
walk(path) goes through a directory and everything below it, a
directory before its contents:
var it: fs.WalkIter = fs.walk("project") or { return 1; };
for (e in it) {
if (e.kind == fs.FileKind.Dir && bytes.eq(path.basename(e.path), ".git")) {
it.skip_dir(); // don't go in there
continue;
}
if (e.kind == fs.FileKind.File) { io.println("{e.depth} {e.path}"); }
}Each entry is a WalkEntry { path: string; kind: FileKind; depth: i64; }:
path is the root you gave joined with the entry’s path below it
(project/src/main.tape), depth is 1 for the root’s own entries. Within
one directory the order is the file system’s. Symbolic links are listed
but never followed. skip_dir() right after a directory keeps the walk
out of it. A directory inside the tree that can’t be read is skipped; only
the root’s errors are reported. Like read_dir, the walk closes itself at
the end; call it.close() if you stop early.
Links and permissions
| Function | Does |
|---|---|
symlink(target, link) -> void or io.IoError | Make a symbolic link at link pointing to target |
read_link(path) -> string or io.IoError | A link’s target, as stored |
set_read_only(path, ro: bool) -> void or io.IoError | Make a file read-only, or writable again |
set_mode(path, mode: i64) -> void or io.IoError | Set a file’s permission bits (0o644, 0o755, …) |
chown(path, uid: i64, gid: i64) -> void or io.IoError | Set a file’s owner and group; -1 keeps one |
fs.symlink("config-v2.ini", "config.ini") or { return 1; };
let t: string = fs.read_link("config.ini") or { return 1; }; // "config-v2.ini"The target need not exist, and a relative target is relative to the
link’s directory. read_link gives the text back without resolving it;
on a file that isn’t a link it is InvalidInput. Windows only makes links
in developer mode (or for an administrator): otherwise symlink is
PermissionDenied.
set_read_only(p, true) takes away everyone’s write permission (on
Windows it sets the read-only attribute); set_read_only(p, false) gives
the owner write permission back. metadata(p).read_only reads it. On
Windows a read-only file can’t be removed until it is writable again.
set_mode(p, 0o600) sets all the permission bits at once, as chmod
does: the low 12 bits of the mode (read, write and execute for owner,
group and others, and the set-user-ID, set-group-ID and sticky bits); a
mode below 0 or above 0o7777 is InvalidInput. Windows keeps no mode,
only the read-only attribute: there the owner’s write bit (0o200)
decides it (clear makes the file read-only, set makes it writable) and
the other bits are ignored.
chown(p, uid, gid) gives the file to another user and group, as chown
does; -1 leaves the owner or the group as it is. Giving a file away
usually takes root (PermissionDenied otherwise). Windows owners aren’t
numbers: there chown is Unsupported.
fs.write_file(key_path, key) or { return 1; };
fs.set_mode(key_path, 0o600) or { return 1; }; // only the owner reads it
fs.chown(key_path, service_uid, -1) or { return 1; }; // run as root: hand it overBoth follow symbolic links: they change the file a link points to.
Free space and flushing
pub struct Space { total: i64; free: i64; available: i64; }| Function | Does |
|---|---|
space(path) -> Space or io.IoError | The size and free bytes of the file system holding path |
sync() -> void or io.IoError | Flush everything written to every file system to its disk |
let sp: fs.Space = fs.space(data_dir) or { return 1; };
if (sp.available < 1 << 30) { io.eprintln("less than 1 GiB left"); }total is the file system’s size, free its unused bytes, and
available what this program’s user can still write: less than free
where some space is kept for root or a quota applies. path is any file
or directory on it. On Windows space asks about the drive (or mounted
folder) holding path.
sync() asks the system to write every file’s data out, as the sync
command does; to wait for one file’s data, use f.sync() on its File.
Windows has no system-wide flush: there sync is Unsupported.
Metadata
pub struct Metadata { kind: FileKind; size: i64; modified_ns: i64; read_only: bool; mode: i64 = -1; uid: i64 = -1; }
pub enum FileKind : u8 { File = 0; Dir = 1; Symlink = 2; Other = 3; }modified_ns is the last modification time in nanoseconds since
1970-01-01 UTC, as precise as the file system keeps it; time.from_unix_nanos
turns it into a date. read_only means nobody may write the file.
mode is the permission bits (0o644, 0o700: what set_mode sets)
and uid the owner’s user id, to compare with os.uid(); both
are -1 on Windows, where files have no Unix mode and owners are SIDs.
metadata follows symbolic links, so its kind is never Symlink;
link_metadata doesn’t, and a DirEntry’s kind is the entry itself, so
theirs can be.
Before trusting a directory someone else could have made first (one in the shared temporary directory), check it without following a link:
let me: ?i64 = os.uid(); // null on Windows
if (me == null) { return 1; }
fs.mkdir(dir, 0o700) or { if (err != io.IoError.AlreadyExists) { return 1; } };
let m: fs.Metadata = fs.link_metadata(dir) or { return 1; };
if (m.kind != fs.FileKind.Dir || m.uid != me! || (m.mode & 0o077) != 0) {
return 1; // a link, another user's, or open to others
}Platforms
Windows, Linux and macOS support all of fs; names are UTF-8 everywhere
(converted to UTF-16 on Windows). Long paths work on Windows too: a path
of 248 characters or more is passed to Windows in its long form
(\\?\C:\...), so the old 260-character limit doesn’t apply. On Uusi (Leivos) an absolute path such as
/system/fonts/x.ttf is a file of Leivos’s storaged: opening, reading,
writing, seeking, metadata (kind, size and modification time), directories,
listings and rename (which replaces a file atomically) work; cwd and
chdir are Unsupported, and without storaged
an absolute path is NotFound. Any other path is the kernel’s (a file of
the boot bundle, read only). walk works there as read_dir does; links,
set_read_only, set_mode, chown, space, fs.sync, truncate,
File.sync and the locks are Unsupported.
Last modified: