Skip to content
Kavachकवच

Files

Also known as: file io read write disk path filesystem open save load stream lines log csv chunks big file read ahead

● Intermediate5 minBefore this: Errors, For LoopSpec 14.3

std.fs reads and writes files and folders. Paths are text, relative to the folder the program runs in.

use std.fs

fn main() ! Error {
    try fs.write_text("notes.txt", "first line\nsecond line\n")
    try fs.append_text("notes.txt", "third line\n")
    print(try fs.read_text("notes.txt"))
    for line in try fs.lines("notes.txt") {
        print(line.upper())
    }
    print(fs.exists("notes.txt"))
    try fs.remove("notes.txt")
    print(fs.exists("notes.txt"))
}

The program ran and printed:

kavach run write-read.kav

first linesecond linethird line FIRST LINESECOND LINETHIRD LINEtruefalse
write-read.kav: Kavach code, then what running it prints

Every function

FunctionGives
fs.read_text(path) -> String ! FsErrorThe file's text (it must be UTF-8)
fs.write_text(path, text) ! FsErrorReplaces the file atomically: the new text goes to a temporary file that is then renamed, so a crash never leaves half a file
fs.append_text(path, text) ! FsErrorAdds to the end, creating the file if needed
fs.read_bytes(path) -> Bytes ! FsErrorThe file's contents, any bytes (2.13)
fs.write_bytes(path, data) ! FsErrorReplaces the file atomically, like write_text
fs.write_durable(path, data) ! FsErrorReplaces the file atomically and forces it to the disk (fsync on the file, then on its folder) before returning: after it, a power cut keeps the new contents. Storage engines build on this
fs.lines(path) ! FsErrorThe file's lines, read as a for loop goes, without their line ending (\n or \r\n)
fs.chunks(path, size) ! FsErrorThe file's bytes in Bytes pieces of size (the last may be shorter), read as a for loop goes
fs.exists(path) -> BoolWhether a file or folder is there
fs.list(folder) -> [String] ! FsErrorThe names in a folder, sorted
fs.remove(path) ! FsErrorDeletes a file or an empty folder
fs.create_dir(path) ! FsErrorCreates a folder and any missing parents
fs.info(path) -> FileInfo ! FsErrorWhat is at path: its kind, size, last change and permissions (below). A link is described itself, not what it points to
fs.set_read_only(path, read_only) ! FsErrorMakes a file read-only, or writable again, on every system
fs.set_permissions(path, mode) ! FsErrorSets the Unix permission bits, written in octal: 0o644, 0o755. Windows keeps only whether the owner may write: without that bit the file is read-only
fs.rename(from, to) ! FsErrorMoves or renames a file or folder; a file already at to is replaced
fs.copy(from, to) ! FsErrorCopies a file, with its permissions; a file already at to is replaced
fs.remove_all(path) ! FsErrorDeletes a folder and everything in it, or a file
fs.symlink(target, link) ! FsErrorMakes a symbolic link at link that points to target, kept as written (a relative target is relative to the link's folder). With uses Fs("…") (8.1) both must be inside its folders. Windows allows it only in Developer Mode or with administrator rights; otherwise it fails with Denied

When it fails

A file operation can fail: the file isn't there, or you may not read it. It then gives an FsError: NotFound(path), Denied(path) or Failed(path, reason). Match on it to handle each case:

use std.fs

fn main() {
    const config = fs.read_text("app.toml") catch e => match e {
        fs.NotFound(path) => {
            print("no {path} yet, using defaults")
            ""
        }
        _ => panic("can't read app.toml")
    }
    print(config.len())
}

The program ran and printed:

kavach run missing.kav

no app.toml yet, using defaults0
missing.kav: Kavach code, then what running it prints

Reading or writing files needs the Fs capability. A pub function says so with uses Fs, or only uses Fs.read: see Narrower file access.

One page for each form

Try it yourself

Write hello.txt with the text Namaste, read it back and print it.
Show the answer

try fs.write_text("hello.txt", "Namaste"), then print(try fs.read_text("hello.txt")), in a main marked ! Error.

Check yourself

QUIZ 1 / 1pick one
The power goes off while fs.write_text is replacing a file. What is in the file afterwards?