File.create
func File.create(path: string, replace: bool = true): Result[File.Handle, Error]File.create opens the file at path for writing, creating it or truncating what it held. With replace false it creates the file only when nothing is at path, and is otherwise Err.
Details
- The file is truncated as soon as
File.createreturns, before anything is written. A file that exists keeps its mode; a new one gets0o666less the umask,0o644under the usual umask022. - The handle is for writing only. A read from it is
Err. - Close the handle with
File.close, which can fail too. File.closehands the data to the OS but does not wait for the disk;File.syncdoes.File.createfollows a symbolic link atpathand writes its target.- With
replace: false, anything atpathmakes itErr, a directory or a link included, even a link that leads nowhere. The check and the creation are one atomic step.
Basic examples
Create a file, write to it, and close it:
let out = try File.create("notes.txt")
defer { out.close() }
try out.writeLine("buy milk")
try out.writeLine("call Ann")
try out.close()
println(try File.read("notes.txt"))buy milk
call AnnFile.create replaces what the file held:
try File.write("todo.txt", "old list")
let out = try File.create("todo.txt")
defer { out.close() }
println(File.read("todo.txt"))
try out.writeText("new list")
try out.close()
println(File.read("todo.txt"))Ok{ value: "" }
Ok{ value: "new list" }Refuse to replace a file that exists:
try File.write("draft.txt", "keep me")
println(File.create("draft.txt", replace: false))Err{ error: Error{ message: "open draft.txt: file exists" } }Scope
A file that exists keeps its mode when File.create truncates it:
try File.write("secret.txt", "old token")
try File.chmod("secret.txt", 0o600)
let out = try File.create("secret.txt")
defer { out.close() }
try out.writeText("new token")
try out.close()
let info = try File.stat("secret.txt")
println(String.fromInt(info.mode, base: 8))600A path under a directory that is not there is Err. Make the directory with File.mkdir first:
println(File.create("logs/today.log"))
try File.mkdir("logs")
let out = try File.create("logs/today.log")
defer { out.close() }
try out.close()
println(File.exists("logs/today.log"))Err{ error: Error{ message: "open logs/today.log: no such file or directory" } }
trueA directory at path is Err:
try File.mkdir("cache")
println(File.create("cache"))Err{ error: Error{ message: "open cache: is a directory" } }A symbolic link at path is followed, so the write goes to its target:
try File.write("target.txt", "old")
try File.symlink("target.txt", "current.txt")
let out = try File.create("current.txt")
defer { out.close() }
try out.writeText("new")
try out.close()
println(File.read("target.txt"))Ok{ value: "new" }Named arguments
replace
With replace: false, File.create makes the file only when nothing is at path:
let out = try File.create("fresh.txt", replace: false)
defer { out.close() }
try out.writeText("first")
try out.close()
println(File.create("fresh.txt", replace: false))
println(File.read("fresh.txt"))Err{ error: Error{ message: "open fresh.txt: file exists" } }
Ok{ value: "first" }A link at path counts as something there, even one that leads nowhere, and it is not followed:
try File.symlink("missing.txt", "planted.txt")
println(File.create("planted.txt", replace: false))
println(File.exists("missing.txt"))Err{ error: Error{ message: "open planted.txt: file exists" } }
falseApplications
Write many lines through File.buffered, and close it explicitly so that a failed write-out is reported:
func writeReport(path: string, rows: Array[string]): Result[void, Error] {
let out = File.buffered(try File.create(path))
defer { out.close() }
for row in rows {
try out.writeLine(row)
}
out.close()
}
try writeReport("report.csv", ["name,score", "Ann,31", "Bob,27"])
println(try File.read("report.csv"))name,score
Ann,31
Bob,27Pick the first free name, without overwriting the reports of earlier runs. replace: false makes the check and the creation one step, so two programs never get the same name:
func claim(base: string): Result[string, Error] {
for n in Iter.range(1, 100) {
let name = "${base}-${n}.txt"
let out = File.create(name, replace: false)
if out is Err {
if File.exists(name) { continue }
return Result.err(out.error)
}
try out.value.close()
return Result.ok(name)
}
Result.fail("no free name for ${base}")
}
println(claim("run"))
println(claim("run"))Ok{ value: "run-1.txt" }
Ok{ value: "run-2.txt" }Add context to the error with Result.wrapErr:
func save(path: string, text: string): Result[void, Error] {
let out = try (File.create(path) | Result.wrapErr("save"))
defer { out.close() }
try out.writeText(text)
out.close()
}
println(save("nowhere/out.txt", "hello"))Err{ error: Error{ message: "save: open nowhere/out.txt: no such file or directory" } }Replace a file only once its new contents are complete. Write them to a temporary file beside it, then rename that over the old one, so a reader sees the old file or the new one. The new file has mode 0o600 from File.tempFile, not the mode the old one had:
func replaceFile(path: string, text: string): Result[void, Error] {
let tmp = try File.tempFile(".page-*", dir: Path.dir(path))
defer { File.remove(tmp) }
try File.write(tmp, text)
File.rename(tmp, path)
}
try File.write("page.html", "<p>old</p>")
try replaceFile("page.html", "<p>new</p>")
println(File.read("page.html"))
let info = try File.stat("page.html")
println(String.fromInt(info.mode, base: 8))Ok{ value: "<p>new</p>" }
600The 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.
Properties and relations
A file created and closed without a write is empty:
let out = try File.create("empty.txt")
defer { out.close() }
try out.close()
let text = try File.read("empty.txt")
assert(text.isEmpty())File.create, File.writeText, and File.close write what File.write writes in one call:
let out = try File.create("a.txt")
defer { out.close() }
try out.writeText("same")
try out.close()
try File.write("b.txt", "same")
assert(File.read("a.txt") == File.read("b.txt"))Possible issues
The handle is for writing. Open the file again with File.open to read it:
let out = try File.create("log.txt")
defer { out.close() }
try out.writeLine("started")
println(out.readAll())
try out.close()Err{ error: Error{ message: "the file is not open for reading" } }File.create truncates the file before the first write. When the program fails before it writes, the old contents are gone. Write to a temporary file beside it with File.tempFile and File.rename it into place to keep the old file until the new one is complete, as replaceFile does in Applications:
func render(): Result[string, Error] {
Result.fail("template missing")
}
try File.write("page.html", "<p>old</p>")
let out = try File.create("page.html")
defer { out.close() }
println(render())
println(File.read("page.html"))Err{ error: Error{ message: "template missing" } }
Ok{ value: "" }The Err of replace: false carries only the OS's message, with nothing a program can test. Check File.exists after it to tell an existing file from other failures, as claim does in Applications.
See also
File.open, File.append, File.write, File.close, File.buffered, File.writeLine, File.writeText, File.tempFile, File.rename, File.mkdir, File.sync
