85 Writing and reading a file
CreateNew claims a fresh filename and fails rather than overwriting an existing file. The writer is closed in finally before a bounded UTF-8 read returns the text.
norm
import std.filesystem.FileWriteMode
import std.filesystem.Path
import std.filesystem.openWrite
import std.filesystem.readText
import std.io.TextEncoding
import std.io.encodeText
main() {
Path note = Path(value: "note.txt")
var writer = openWrite(path: note, mode: FileWriteMode.CreateNew)
try {
var content = encodeText(
text: "Learn Norm",
encoding: TextEncoding.Utf8
)
writer.write(content)
} finally {
writer.close()
}
String text = readText(
path: note,
encoding: TextEncoding.Utf8,
maximumBytes: 1024
)
printLine(text)
}From the Norm repository root, use a new, empty scratch directory:
sh
mkdir .tmp/norm-file-lesson
cd .tmp/norm-file-lesson
norm run ../../norm/tests/docs/libraries/files/write_read.normExpected output:
text
Learn NormThe program leaves its own note.txt in that scratch directory for the next lesson. Repeating the write without removing it fails while opening the existing file; the file is not overwritten.
Try it: Run the command twice and inspect the second failure.
Precise rules: Filesystem API.