Standard library · System and tools

fs

Reading, writing, copying and moving files, file information, times and permissions, and MD5 and SHA digests.

import fs

The fs package is everything you need to work with one file: read it whole or as lines, write, append, replace it safely, copy, move and delete it, look up its size, times and permissions, change the permissions, hash it and guess its MIME type. One import is enough: import fs, then fs.ReadText(path). For folders use fs.dir, for paths fs.path, and for streaming a large file the handle functions of io. The simpler os package covers whole-file reads, folder listings and existence checks.

The old fs.file package still works but is deprecated: it forwards every call to fs. In new code write import fs and fs.ReadText instead of import fs.file and file.ReadText.

Writes return the number of bytes written, or -1. Reads return empty text (an empty vector for ReadAllBytes) when the file cannot be opened, the same as for an empty file; ask Exists when the difference matters.

What people get wrong:

•

Reading binary data as text. ReadText, ReadAll, ReadBytes and WriteBytes go through a str, which ends at the first zero byte, so they cut a binary file short. For images, archives and other binary data use ReadAllBytes and WriteAllBytes, which carry every byte in a Vector<u8>. The digest functions always hash the file's real bytes.

•

Expecting Move to cross disks. It is a rename and fails between file systems; fs.dir.Move falls back to copying, or copy and delete yourself.

•

Assuming AtomicWrite keeps the old file's permissions. It writes a new file, which gets the default permissions; a file you had narrowed to 0o600 becomes readable again unless you Chmod it after each save.

•

Using Exists to mean "is a file". It is true for directories too; combine it with fs.dir.IsDir.

Times are whole seconds since the start of 1970 (Unix time), as an i64. Every function returns -1 when the path does not exist or the system cannot answer.

Write permissions in octal, such as 0o644, meaning the owner reads and writes and everyone else reads. Permissions returns the mode as that same number, so fs.Permissions(p) == 0o644 is true for such a file and Chmod(p, Permissions(p)) changes nothing. Printed as an ordinary number it shows in decimal (0o644 prints as 420); compare it with an 0o literal, or pick the three digits out with (p >> 6) & 7, (p >> 3) & 7 and p & 7.

Read a settings file line by line

ReadLines splits a file at its line breaks and drops a trailing \r, so a file saved on Windows reads the same as one saved on Linux. That makes simple key = value files easy: trim each line, skip blank lines and comments, and split at the first =.

fs-guide-config.salam
import fs
import str

func main:
    fs.WriteText("app.conf", "# shop settings\nname = Corner Shop\n\nport = 8080\ncurrency = IRR\n")
    settings := HashMap {} as HashMap<str, str>
    each line in fs.ReadLines("app.conf"):
        t := line.Trim()
        if t.Len() == 0 or str.StartsWith(t, "#"): continue end
        eq_at := str.IndexOf(t, "=")
        if eq_at < 0: continue end
        settings.Put(t.Substr(0, eq_at).Trim(), t.Substr(eq_at + 1, t.Len() - eq_at - 1).Trim())
    end
    println settings.Size(), "settings"
    println "name:", settings.Get("name")
    println "port:", settings.Get("port")
    fs.Delete("app.conf")
end
Output
3 settings
name: Corner Shop
port: 8080

For a format with sections, quoting or nesting, use a real parser such as encoding.toml, encoding.json or encoding.envfile.

Append to a log

Append opens the file, adds the text at the end and closes it again, and creates the file on the first call. Each call is a separate open and close, which is fine for a line now and then. For a busy log, open the file once with Open(p, "ab"), write through io.Write and Close it at the end.

fs-guide-log.salam
import fs

func log(line: str):
    fs.Append("app.log", line.Concat("\n"))
end

func main:
    log("started")
    log("loaded 3 orders")
    log("sent invoice 1042")
    log("stopped")
    lines := fs.ReadLines("app.log")
    println "log has", lines.Len(), "lines,", fs.Size("app.log"), "bytes"
    println "last two:"
    mut i := lines.Len() - 2
    until i < lines.Len():
        println " ", lines.Get(i)
        i++
    end
    fs.Delete("app.log")
end
Output
log has 4 lines, 50 bytes
last two:
  sent invoice 1042
  stopped

Check that a file arrived intact

Download pages often publish a SHA-256 digest next to each file. Compute the digest of your copy with Sha256Hex and compare the two: a change of even one byte gives a completely different digest. Md5Hex and Sha1Hex are fine for noticing accidental changes, such as a cache key, but anyone can build two different files with the same MD5 or SHA-1 on purpose, so do not trust them against an attacker.

fs-guide-checksum.salam
import fs

func verify(p: str): bool:
    want := fs.ReadText(p.Concat(".sha256")).Trim()
    ret fs.Sha256Hex(p) == want
end

func main:
    fs.WriteBytes("release.tar", "pretend this is a release archive")
    fs.WriteText("release.tar.sha256", fs.Sha256Hex("release.tar").Concat("\n"))
    println "intact:", verify("release.tar")
    fs.Append("release.tar", "!")
    println "after a change:", verify("release.tar")
    fs.Delete("release.tar")
    fs.Delete("release.tar.sha256")
end
Output
intact: true
after a change: false

The digest functions hash the file's exact bytes, zero bytes included, so they give the same answer as sha256sum for archives and images as well as text. They read the whole file into memory first; for a file too large for that, read it in pieces through Open and feed them to Sha256Update in crypto. A file that cannot be read gives an empty string, not the digest of empty content.

Save without losing the old version

AtomicWrite writes the new content to name.tmp next to the target and then renames it over the target in one step. A program that crashes in the middle leaves either the old file or the new one, never half of each. It does not flush the data to the disk first, so after a power cut a file saved a moment earlier can still be lost on some file systems, and two programs saving the same file at once share the same .tmp name. Copying the old file to .bak first also keeps one previous version. When the folder does not exist, AtomicWrite returns -1 and leaves its message in os.error.

fs-guide-save.salam
import fs
import os.error

func save(p: str, data: str): bool:
    if fs.Exists(p): fs.Copy(p, p.Concat(".bak")) end
    if fs.AtomicWrite(p, data) != 0:
        println "save failed:", error.LastMessage()
        ret false
    end
    ret true
end

func main:
    save("profile.json", "{\"name\": \"Sara\"}")
    save("profile.json", "{\"name\": \"Sara\", \"city\": \"Tabriz\"}")
    println "current:", fs.ReadText("profile.json")
    println "backup: ", fs.ReadText("profile.json.bak")
    println "temp file left:", fs.Exists("profile.json.tmp")
    save("no-such-dir/profile.json", "{}")
    fs.Delete("profile.json")
    fs.Delete("profile.json.bak")
end
Output
current: {"name": "Sara", "city": "Tabriz"}
backup:  {"name": "Sara"}
temp file left: false
save failed: atomic write failed

Serve files with the right type

A web server has to send a Content-Type with each file. MimeType picks it from the extension alone, without upper and lower case mattering, and knows the common web, image, audio, video and archive types; anything else is application/octet-stream, which browsers download instead of showing. Extension keeps the dot and the original case, and is empty when the name has no extension.

fs-guide-mime.salam
import fs

func main:
    each name in [
        "index.html", "app.js", "logo.SVG", "photo.jpeg", "data.json", "notes", "backup.7z"
    ]:
        ext := fs.Extension(name)
        if ext == "": println name, "(no extension)", fs.MimeType(name)
        else:
            println name, ext, fs.MimeType(name)
        end
    end
end
Output
index.html .html text/html
app.js .js text/javascript
logo.SVG .SVG image/svg+xml
photo.jpeg .jpeg image/jpeg
data.json .json application/json
notes (no extension) application/octet-stream
backup.7z .7z application/octet-stream

An HTTP server usually wants net.mime instead: its MimeType adds ; charset=utf-8 to text types and knows web fonts, and the package also parses Content-Type headers and multipart bodies.

Keep a secret file private

A new file gets the system default permissions, usually 644, which lets every account on the machine read it. For tokens, keys and passwords, write the file and then narrow it to 0o600. Chmod and Permissions use the same number, so (p & 0o077) == 0 below means that the group and everyone else have no rights at all.

fs-guide-private.salam
import fs

func octal(p: int): str:
    ret "0o" + ((p >> 6) & 7) + ((p >> 3) & 7) + (p & 7)
end

func main:
    fs.WriteText("token.txt", "s3cr3t")
    fs.Chmod("token.txt", 0o644)
    println "before:", octal(fs.Permissions("token.txt"))
    fs.Chmod("token.txt", 0o600)
    p := fs.Permissions("token.txt")
    println "after: ", octal(p)
    if (p & 0o077) == 0:
        println "only the owner can read it"
    end
    fs.Delete("token.txt")
end
Output
before: 0o644
after:  0o600
only the owner can read it

Reading the permission digits

The three digits are for the owner, the group and everyone else, in that order. Inside one digit, 4 means read, 2 means write and 1 means execute, and the digit is their sum:

DigitLettersMeaning
7rwxread, write and run
6rw-read and write
5r-xread and run
4r--read only
0---nothing

This example turns the number into the letters that ls -l prints. A script needs the execute bit for its owner (0o755 or 0o700) before the shell runs it, and a directory needs it before anyone can open it.

fs-guide-rwx.salam
import fs

func letters(digit: int): str:
    mut out := ""
    if (digit & 4) != 0: out += "r" else:
        out += "-"
    end
    if (digit & 2) != 0: out += "w" else:
        out += "-"
    end
    if (digit & 1) != 0: out += "x" else:
        out += "-"
    end
    ret out
end

func show(p: int): str:
    ret letters((p >> 6) & 7) + letters((p >> 3) & 7) + letters(p & 7)
end

func octal(p: int): str:
    ret "0o" + ((p >> 6) & 7) + ((p >> 3) & 7) + (p & 7)
end

func main:
    fs.WriteText("deploy.sh", "echo deploying\n")
    each mode in [0o755, 0o750, 0o644, 0o600]:
        fs.Chmod("deploy.sh", mode)
        p := fs.Permissions("deploy.sh")
        println octal(p), show(p)
    end
    fs.Delete("deploy.sh")
end
Output
0o755 rwxr-xr-x
0o750 rwxr-x---
0o644 rw-r--r--
0o600 rw-------

Rebuild only what changed

ModTime is how build tools such as make decide what to do: an output is out of date when its source changed after the output was written. For a path that does not exist ModTime returns -1, which the example reads as "build it". Times are in whole seconds, so a source and an output written in the same second count as up to date. That is the right answer here, because the output was written after the source.

fs-guide-rebuild.salam
import fs

func needs_build(src: str, out: str): bool:
    built := fs.ModTime(out)
    if built < 0: ret true end
    ret fs.ModTime(src) > built
end

func main:
    fs.WriteText("page.md", "# Hello\n")
    println "first run, build:", needs_build("page.md", "page.html")
    fs.WriteText("page.html", "<h1>Hello</h1>\n")
    println "after building, build:", needs_build("page.md", "page.html")
    fs.Delete("page.html")
    println "output deleted, build:", needs_build("page.md", "page.html")
    fs.Delete("page.md")
end
Output
first run, build: true
after building, build: false
output deleted, build: true

Platform notes

•

CreatedTime is 0 where the file system does not record a creation time, which is common on Linux. Use ModTime when you need a value that is always there.

•

The time functions, Permissions and Stat ask the system directly (statx on Linux, stat on Android, macOS and FreeBSD), so they are cheap enough to call in a loop. They follow symbolic links. OpenBSD and NetBSD still run the system stat command through the shell.

•

Windows has no Unix permission bits, only a read only flag, so Chmod can only switch that flag (the owner's write bit, 0o200), and Permissions returns 0o444 for a read only file and 0o666 otherwise, with the execute bits added for directories and programs. Write permission logic for Unix and test it there.

Which function for which job

JobFunction
Read a small text file wholeReadText, or ReadLines for a vector of lines
Read only the start of a text fileReadBytes
Read or write binary data, such as an image or an archiveReadAllBytes, WriteAllBytes
Replace a file's contentWriteText, or AtomicWrite when the file matters
Add to the end of a fileAppend
Work through a big file piece by pieceOpen, then the io functions, then Close
Size, times and permissions in one callStat
Duplicate, move or deleteCopy, Move (or Rename), Delete
Check a downloadSha256Hex
Content type for a web responseMimeType

Types

FileInfo

#
struct FileInfo

Everything about a file.

NameTypeDescription
sizei64 = 0The size in bytes.
mod_timei64 = 0When it was last changed.
accessed_timei64 = 0When it was last read.
created_timei64 = 0When it was created.
permissionsint = 0The permission bits, the same number Chmod takes, such as 0o644.
existsbool = falseTrue when the path exists (a directory counts); the other fields are 0 when it does not.
fs-Stat.salam
import fs

func main:
    fs.WriteText("picture.png", "PNG")
    info := fs.Stat("picture.png")
    println info.exists, info.size, info.mod_time > 0, info.permissions > 0
    println fs.Size("picture.png"), fs.Exists("picture.png")
    println fs.ModTime("picture.png") > 0,
        fs.AccessedTime("picture.png") > 0,
        fs.CreatedTime("picture.png") >= 0
    fs.Chmod("picture.png", 0o600)
    println fs.Permissions("picture.png") == 0o600, fs.Permissions("picture.png")
    println fs.Extension("picture.png"), fs.MimeType("picture.png"), fs.MimeType("letter.pdf")
    println fs.Stat("missing.txt").exists
end
Output
true 3 true true
3 true
true true true
true 384
.png image/png application/pdf
false

Functions

Open

#
func Open(path: str, mode: str): File*

Opens a file to work through it piece by piece; the modes are the same as os.Open. Returns null when it cannot.

fs-ReadText.salam
import fs

func main:
    fs.WriteText("poem.txt", "The children of Adam are limbs of one body\n")
    fs.Append("poem.txt", "having been created of one essence\n")
    print fs.ReadText("poem.txt")
    println fs.ReadAll("poem.txt") == fs.ReadText("poem.txt")
    lines := fs.ReadLines("poem.txt")
    println lines.Len(), lines.Get(1)
    fs.WriteBytes("data.bin", "ABCDEF")
    println fs.ReadBytes("data.bin", 3)
    fs.AtomicWrite("settings.txt", "language=english")
    println fs.ReadText("settings.txt")
    f := fs.Open("poem.txt", "rb")
    println f.Readline()
    fs.Close(f)
end
Output
The children of Adam are limbs of one body
having been created of one essence
true
2 having been created of one essence
ABC
language=english
The children of Adam are limbs of one body

Close

#
func Close(f: File*)

Closes an open file.

The example for this item is shown with the ones above: fs-ReadText.salam

ReadText

#
func ReadText(path: str): str

Reads the whole file as text; empty when the file cannot be opened.

The example for this item is shown with the ones above: fs-ReadText.salam

ReadAll

#
func ReadAll(path: str): str

Reads the whole file, the same as ReadText. The result is a str, so a binary file is cut at its first zero byte; use ReadAllBytes for binary files.

The example for this item is shown with the ones above: fs-ReadText.salam

ReadBytes

#
func ReadBytes(path: str, n: int): str

Reads up to the first n bytes of the file as a str, so the result stops at the first zero byte. For binary headers read the file with ReadAllBytes.

The example for this item is shown with the ones above: fs-ReadText.salam

ReadLines

#
func ReadLines(path: str): Vector<str>

Returns the file's lines in a vector, without the line breaks and with a trailing \r removed.

The example for this item is shown with the ones above: fs-ReadText.salam

WriteText

#
func WriteText(path: str, data: str): int

Writes text to a file, creating it or replacing what was there; returns the bytes written, or -1.

The example for this item is shown with the ones above: fs-ReadText.salam

WriteBytes

#
func WriteBytes(path: str, data: str): int

The same as WriteText. The data is a str, so it stops at the first zero byte and is not safe for binary content; use WriteAllBytes for that.

The example for this item is shown with the ones above: fs-ReadText.salam

ReadAllBytes

#
func ReadAllBytes(path: str): Vector<u8>

Reads every byte of the file, zero bytes included, into a Vector<u8> that you free. Empty when the file is empty or cannot be read; a failure is also recorded in os.error. Files of 2 GB and more are refused.

fs-ReadAllBytes.salam
import fs

func main:
    mut png := Vector {} as Vector<u8>
    defer png.Free()
    each b in [137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13]:
        png.Push(b as u8)
    end
    println fs.WriteAllBytes("header.bin", png)
    back := fs.ReadAllBytes("header.bin")
    defer back.Free()
    println back.Len(), back.Get(1), back.Get(11)
    println fs.Size("header.bin")
    println fs.Sha256Hex("header.bin")
    fs.Delete("header.bin")
end
Output
12
12 80 13
12
218ad85a233eff829618a6865ab681222b734c62d35a32b3eabd5c37d8945f86

WriteAllBytes

#
func WriteAllBytes(path: str, data: Vector<u8>): int

Writes every byte of a Vector<u8> to a file, creating it or replacing what was there; returns the bytes written, or -1 with an os.error record.

The example for this item is shown with the ones above: fs-ReadAllBytes.salam

Append

#
func Append(path: str, data: str): int

Adds to the end of a file, creating it when missing; returns the bytes written, or -1.

The example for this item is shown with the ones above: fs-ReadText.salam

AtomicWrite

#
func AtomicWrite(path: str, data: str): int

Writes path.tmp and renames it over the file, so an interrupted program leaves either the complete new version or the old one, never a half written file. Returns 0 or -1 (with an os.error record). The new file gets default permissions, and the data is not flushed to disk first.

The example for this item is shown with the ones above: fs-ReadText.salam

Size

#
func Size(p: str): i64

The size of a file in bytes; -1 when it is missing or is a directory.

The example for this item is shown with the ones above: fs-Stat.salam

Extension

#
func Extension(p: str): str

The file's extension with its dot and its original case, such as .JPG; empty when there is none.

The example for this item is shown with the ones above: fs-Stat.salam

MimeType

#
func MimeType(p: str): str

The file's MIME type from its extension, ignoring case, for serving it over the web; application/octet-stream for an unknown extension. The file is not opened.

The example for this item is shown with the ones above: fs-Stat.salam

Stat

#
func Stat(p: str): FileInfo

Everything about a file at once, from one system call.

The example for this item is shown with the ones above: fs-Stat.salam

Copy

#
func Copy(src: str, dst: str): int

Copies a file's bytes, replacing the destination; permissions are not copied. 0 or -1.

fs-Copy.salam
import fs

func main:
    fs.WriteText("original.txt", "hello")
    fs.Copy("original.txt", "copy.txt")
    fs.Move("copy.txt", "moved.txt")
    fs.Rename("moved.txt", "final.txt")
    println fs.Exists("copy.txt"), fs.Exists("final.txt"), fs.ReadText("final.txt")
    fs.Delete("final.txt")
    println fs.Exists("final.txt")
end
Output
false true hello
false

Move

#
func Move(src: str, dst: str): int

Moves a file by renaming it, so it fails (-1) between two disks. fs.dir.Move can copy instead.

The example for this item is shown with the ones above: fs-Copy.salam

Rename

#
func Rename(src: str, dst: str): int

Renames a file; the same as Move.

The example for this item is shown with the ones above: fs-Copy.salam

Delete

#
func Delete(p: str): int

Deletes a file; 0 or -1. Any failure is recorded in os.error as FileNotFound, a missing permission included.

The example for this item is shown with the ones above: fs-Copy.salam

Exists

#
func Exists(p: str): bool

True when the path exists, file or directory.

The example for this item is shown with the ones above: fs-Stat.salam

Md5Hex

#
func Md5Hex(p: str): str

The MD5 digest of the file's content; for a quick comparison only, not for security. Every byte counts, zero bytes included; empty when the file cannot be read.

fs-Sha256Hex.salam
import fs

func main:
    fs.WriteText("message.txt", "abc")
    println fs.Md5Hex("message.txt")
    println fs.Sha1Hex("message.txt")
    println fs.Sha256Hex("message.txt")
    println fs.Sha512Hex("message.txt").Len()
end
Output
900150983cd24fb0d6963f7d28e17f72
a9993e364706816aba3e25717850c26c9cd0d89d
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
128

Sha1Hex

#
func Sha1Hex(p: str): str

The SHA-1 digest of the file's content. Every byte counts, zero bytes included; empty when the file cannot be read.

The example for this item is shown with the ones above: fs-Sha256Hex.salam

Sha256Hex

#
func Sha256Hex(p: str): str

The SHA-256 digest of the file's content, for checking that a download arrived intact. Every byte counts, zero bytes included; empty when the file cannot be read.

The example for this item is shown with the ones above: fs-Sha256Hex.salam

Sha512Hex

#
func Sha512Hex(p: str): str

The SHA-512 digest of the file's content. Every byte counts, zero bytes included; empty when the file cannot be read.

The example for this item is shown with the ones above: fs-Sha256Hex.salam

ModTime

#
func ModTime(path: str): i64

When the file's content was last changed, in Unix seconds; -1 when the path does not exist.

The example for this item is shown with the ones above: fs-Stat.salam

AccessedTime

#
func AccessedTime(path: str): i64

When the file was last read, in Unix seconds. Many systems update it lazily or not at all (noatime), so do not rely on it.

fs-ModTime.salam
import fs

func main:
    fs.WriteText("report.txt", "hello")
    t := fs.ModTime("report.txt")
    println t > 0, fs.AccessedTime("report.txt") > 0, fs.CreatedTime("report.txt") >= 0
    fs.Chmod("report.txt", 0o644)
    println fs.Permissions("report.txt") == 0o644, fs.Permissions("report.txt")
end
Output
true true true
true 420

CreatedTime

#
func CreatedTime(path: str): i64

When the file was created, in Unix seconds, or zero where the file system does not keep it.

The example for this item is shown with the ones above: fs-ModTime.salam

Chmod

#
func Chmod(path: str, mode: int): int

Changes a file's permissions; give them in octal, such as 0o644, or pass back what Permissions returned. Returns 0 on success and -1 on failure. On Windows only the read only flag can change.

The example for this item is shown with the ones above: fs-ModTime.salam

Permissions

#
func Permissions(path: str): int

A file's permission bits (with setuid, setgid and sticky), the same number Chmod takes: 0o644 for a file only its owner can change. -1 when the path does not exist. On Windows 0o444 or 0o666.

The example for this item is shown with the ones above: fs-ModTime.salam