File.tempFile
func File.tempFile(pattern: string, dir: string | null = null): Result[string, Error]File.tempFile creates a new empty file, mode 0o600, in dir or the host's temporary directory, and returns its path. Its name is pattern with the last * replaced by a random string, or with the string appended when there is no *. Nothing removes it for the program.
Details
File.tempFilecreates the file only when its name is free, so it never replaces anything, a planted symbolic link included.File.tempFilereturns a path, not a handle. Write to it withFile.writeor open it withFile.create. For a file that must survive a crash, open it withFile.createandFile.syncthe handle before renaming it;File.writereturns no handle to sync.- A
patternthat holds a path separator isErr. Give the directory withdir:instead. diris the host's temporary directory when it isnull:$TMPDIR, or/tmpwhen that is unset, on Unix, and%TEMP%on Windows. The directory must exist.- Nothing removes the file, at exit or later. Remove it yourself, usually with
defer { File.remove(path) }right after the call.Os.exitruns no deferred block.
Basic examples
Create a temporary file, use it, and remove it when the program is done:
let path = try File.tempFile("notes-*.txt")
defer { File.remove(path) }
try File.write(path, "draft")
println(try File.read(path))draftThe random string replaces the *, so the name keeps the prefix and the extension of pattern:
let path = try File.tempFile("report-*.csv")
defer { File.remove(path) }
let name = Path.base(path)
println(name.startsWith("report-"))
println(name.endsWith(".csv"))true
trueScope
Without a *, the random string goes at the end of pattern:
let path = try File.tempFile("job-", dir: ".")
defer { File.remove(path) }
let suffix = Path.base(path).trimPrefix("job-")
println(suffix.isEmpty())falseOnly the last * is replaced; the others stay in the name:
let path = try File.tempFile("a*b*.txt", dir: ".")
defer { File.remove(path) }
println(Path.base(path).startsWith("a*b"))
println(Path.base(path).contains("*b*"))true
falseThe new file is empty, and only its owner can read and write it:
let path = try File.tempFile("secret-*")
defer { File.remove(path) }
println((try File.read(path)).isEmpty())
let info = try File.stat(path)
println(String.fromInt(info.mode, base: 8))true
600A pattern with a path separator is Err:
println(File.tempFile("cache/entry-*"))Err{ error: Error{ message: "createtemp cache/entry-*: pattern contains path separator" } }Named arguments
dir
With dir:, File.tempFile creates the file in that directory instead of the host's temporary directory:
try File.mkdir("work")
let path = try File.tempFile("job-*.log", dir: "work")
defer { File.remove(path) }
println(Path.dir(path))
println((try File.glob("job-*.log", dir: "work")).length())work
1The directory must exist:
println(File.tempFile("job-*", dir: "missing") is Err)trueApplications
Save a file so that a reader sees the old contents or the new ones, never half a write. Write a temporary file next to the target, in the same directory, then rename it over the target. The deferred File.remove cleans up when a step fails; after the rename nothing is left for it to remove:
func save(path: string, text: string): Result[void, Error] {
let tmp = try File.tempFile(".${Path.base(path)}-*", dir: Path.dir(path))
defer { File.remove(tmp) }
try File.write(tmp, text)
File.rename(tmp, path)
}
try save("config.json", "{\"debug\": false}")
try save("config.json", "{\"debug\": true}")
println(try File.read("config.json"))
println(try File.glob(".config.json-*", hidden: true)){"debug": true}
[]The rename keeps readers from a half-written file but does not wait for the disk; for a file that must survive a crash, sync it first, as Replace a file without a partial write shows.
Hand a function that takes a path some input of your own, without touching the working directory, as a test does. Add context to a failure with Result.wrapErr:
func countLines(path: string): Result[int, Error] {
let text = try File.read(path)
Result.ok(text.split("\n").filter({ !x.isEmpty() }).length())
}
func countText(text: string): Result[int, Error] {
let path = try (File.tempFile("input-*.txt") | Result.wrapErr("count lines"))
defer { File.remove(path) }
try File.write(path, text)
countLines(path)
}
println(countText("one\ntwo\nthree\n"))Ok{ value: 3 }Properties and relations
Every call picks a new name, so two calls with the same pattern never return the same path:
let a = try File.tempFile("same-*")
defer { File.remove(a) }
let b = try File.tempFile("same-*")
defer { File.remove(b) }
assert(a != b)The path lies in dir:
try File.mkdir("out")
let path = try File.tempFile("part-*", dir: "out")
defer { File.remove(path) }
assert(Path.dir(path) == "out")
assert(File.exists(path))Possible issues
The file already exists when File.tempFile returns, so a write with replace: false fails. Write with the default replace: true:
let path = try File.tempFile("out-*", dir: ".")
defer { File.remove(path) }
let refused = File.write(path, "data", replace: false)
println(refused is Err)
println(File.write(path, "data"))true
Ok{ value: void }Os.exit runs no deferred block, so a file meant to be removed by defer stays. Remove it before the exit:
let path = try File.tempFile("run-*")
defer { File.remove(path) }
try File.remove(path)
Os.exit(2)A file made by File.tempFile keeps mode 0o600 when it is renamed into place, so only its owner can read the result:
let target = "shared.txt"
let tmp = try File.tempFile(".shared-*", dir: ".")
defer { File.remove(tmp) }
try File.write(tmp, "hello")
try File.rename(tmp, target)
println(String.fromInt((try File.stat(target)).mode, base: 8))600When others must read the file, set its mode with File.chmod before the rename:
let target = "public.txt"
let tmp = try File.tempFile(".public-*", dir: ".")
defer { File.remove(tmp) }
try File.write(tmp, "hello")
try File.chmod(tmp, 0o644)
try File.rename(tmp, target)
println(String.fromInt((try File.stat(target)).mode, base: 8))644See also
File.tempDir · File.remove · File.removeAll · File.rename · File.write · File.create · File.sync
