fs

tape
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

FunctionDoes
read_file(path) -> string or io.IoErrorThe file’s bytes as a string
write_file(path, data) -> void or io.IoErrorCreate or replace the file
append_file(path, data) -> void or io.IoErrorCreate the file or add to its end
copy_file(src, dst) -> void or io.IoErrorCopy 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):

tape
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
Readread only
Writewrite only
ReadWriteboth
Appendwrite, always at the end
CreationIf the file existsIf it doesn’t
Existingopen itNotFound
OpenOrCreateopen it, keep its contentscreate it
CreateNewAlreadyExistscreate it
Truncateopen it and empty itcreate 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.

MethodDoes
f.read(buf) -> i64 or io.IoErrorRead up to buf.len bytes; 0 at the end
f.write(data) -> i64 or io.IoErrorWrite some of data at the position
f.seek(off, whence) -> i64 or io.IoErrorMove to off from Start, Current or End; returns the new position
f.metadata() -> Metadata or io.IoErrorSize, kind, modification time
f.reader() -> io.Reader, f.writer() -> io.WriterThe 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

MethodDoes
f.truncate(size) -> void or io.IoErrorSet the length: shorter drops the end, longer adds zero bytes; the position stays
f.sync() -> void or io.IoErrorReturn once what was written is on the disk
f.lock(kind: Lock) -> void or io.IoErrorLock the whole file, waiting while someone else holds a conflicting lock
f.try_lock(kind: Lock) -> bool or io.IoErrorThe same without waiting: false when someone else holds it
f.unlock() -> void or io.IoErrorRelease 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.

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

tape
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

FunctionDoes
exists(path) -> boolIs there something at path (following links)?
metadata(path) -> Metadata or io.IoErrorWhat is there (following links)
link_metadata(path) -> Metadata or io.IoErrorWhat 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.IoErrorThe entries of a directory
temp_dir() -> stringA directory for temporary files
tape
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:

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

FunctionDoes
symlink(target, link) -> void or io.IoErrorMake a symbolic link at link pointing to target
read_link(path) -> string or io.IoErrorA link’s target, as stored
set_read_only(path, ro: bool) -> void or io.IoErrorMake a file read-only, or writable again
set_mode(path, mode: i64) -> void or io.IoErrorSet a file’s permission bits (0o644, 0o755, …)
chown(path, uid: i64, gid: i64) -> void or io.IoErrorSet a file’s owner and group; -1 keeps one
tape
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.

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

Both follow symbolic links: they change the file a link points to.

Free space and flushing

tape
pub struct Space { total: i64; free: i64; available: i64; }
FunctionDoes
space(path) -> Space or io.IoErrorThe size and free bytes of the file system holding path
sync() -> void or io.IoErrorFlush everything written to every file system to its disk
tape
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

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

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