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.filesystem.writeText
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)
String nested = "nested/note.txt"
writeText(path: nested, text: "first")
writeText(path: nested, text: text)
printLine(readText(nested))
}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 Norm 世界
Learn Norm 世界The 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.