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
importstrfuncmain:
fs.WriteText("app.conf", "# shop settings\nname = Corner Shop\n\nport = 8080\ncurrency = IRR\n")
settings := HashMap {} asHashMap<str, str>
each line in fs.ReadLines("app.conf"):
t := line.Trim()
if t.Len() == 0orstr.StartsWith(t, "#"): continueend
eq_at := str.IndexOf(t, "=")
if eq_at < 0: continueend
settings.Put(t.Substr(0, eq_at).Trim(), t.Substr(eq_at + 1, t.Len() - eq_at - 1).Trim())
endprintln settings.Size(), "settings"println"name:", settings.Get("name")
println"port:", settings.Get("port")
fs.Delete("app.conf")
end
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
funclog(line: str):
fs.Append("app.log", line.Concat("\n"))
endfuncmain:
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() - 2until 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
funcverify(p: str): bool:
want := fs.ReadText(p.Concat(".sha256")).Trim()
ret fs.Sha256Hex(p) == want
endfuncmain:
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.
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
funcmain:
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)
endendend
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.
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:
Digit
Letters
Meaning
7
rwx
read, write and run
6
rw-
read and write
5
r-x
read and run
4
r--
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
funcletters(digit: int): str:
mut out := ""if (digit & 4) != 0: out += "r"else:
out += "-"endif (digit & 2) != 0: out += "w"else:
out += "-"endif (digit & 1) != 0: out += "x"else:
out += "-"endret out
endfuncshow(p: int): str:
retletters((p >> 6) & 7) + letters((p >> 3) & 7) + letters(p & 7)
endfuncoctal(p: int): str:
ret"0o" + ((p >> 6) & 7) + ((p >> 3) & 7) + (p & 7)
endfuncmain:
fs.WriteText("deploy.sh", "echo deploying\n")
each mode in [0o755, 0o750, 0o644, 0o600]:
fs.Chmod("deploy.sh", mode)
p := fs.Permissions("deploy.sh")
printlnoctal(p), show(p)
end
fs.Delete("deploy.sh")
end
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
funcneeds_build(src: str, out: str): bool:
built := fs.ModTime(out)
if built < 0: rettrueendret fs.ModTime(src) > built
endfuncmain:
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
Job
Function
Read a small text file whole
ReadText, or ReadLines for a vector of lines
Read only the start of a text file
ReadBytes
Read or write binary data, such as an image or an archive
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
funcmain:
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
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
funcmain:
mut png := Vector {} asVector<u8>
defer png.Free()
each b in [137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13]:
png.Push(b asu8)
endprintln 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
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
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
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.
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
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
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