write Text(path: string | Path, text: string) - > Result<(), string>- 모듈
- std.
fs → - 수신자
- 해당 없음
- 최소 인자 수
- 2
- 최대 인자 수
- 2
Declaration and parameters
링크사용 조건
기본 포함 · 미정
Import std.fs in language mode 5.21.
The current compiler selects std/fs.tpz for this language mode. Availability in other released editions and inclusion in each installed distribution are Pending.
수신자
매개변수 제약
Each function accepts a string path or a Path. Strings use the host path syntax. A Path supplies its normalized relative text. Relative paths use the working directory in an ordinary installed CLI invocation. A package host applies its configured filesystem base and capability policy.
Path and payload arguments are evaluated once in source order before the operation starts. The operation acquires and releases its own resources before returning. It does not change a separately opened File cursor.
Empty paths and paths containing NUL return Err containing a string. Missing read targets, incorrect path kinds, permission denial, package capability denial, and host failures use the same error channel. Errors are values. They do not terminate the program unless the caller chooses to propagate or assert them.
An error string identifies the public operation and the supplied path. It also describes the failure condition. Platform wording, operating system error numbers, and localized explanations are not stable API values.
read returns the entire regular file as text. UTF-8 validity and text preservation follow UTF-8 decoding. Empty files return an empty string. Invalid UTF-8 returns Err without a decoded text value.
read returns every byte in order, including zero bytes and bytes that are not valid UTF-8. Empty files return empty Bytes. Reading does not create or modify the file.
write encodes its string as UTF-8. write writes the supplied bytes unchanged. Both create a missing regular file or replace the full contents of an existing regular file. An empty payload creates or truncates the file to zero bytes. No newline or byte order mark is added.
Writes do not create missing parent directories. They follow the host permission and creation policy. Replacing a file with shorter content removes its previous suffix. Success returns Ok(()) after all payload bytes have been accepted.
A write failure may occur after creation, truncation, or a prefix write. Err does not promise rollback, atomic replacement, or persistence across a system crash. Earlier argument effects remain visible.
list returns immediate children sorted by their exact names in ascending Unicode scalar order. It does not return dot or parent pseudoentries, traverse child directories, normalize Unicode names, or fold case. The name field contains the child name without the parent path.
Each entry kind is exactly file, directory, symlink, or other. Classification uses the entry itself and does not follow a symbolic link. For a regular file, sizeBytes is Some of its byte length when that length fits in int. Other kinds and an unrepresentable size use None().
A name that cannot be represented as Unicode, a failure while reading an entry, or a failure obtaining its metadata returns Err for the whole list. No partial array is returned. Separate operations do not provide a filesystem snapshot, so other processes may change a path between calls.
Host access follows symbolic links where the operation addresses their target, subject to host capability checks. A normalized Path is not an authorization token. Use File when operations must retain one open resource and cursor, and std.fs when the operation concerns complete contents or directory entries.
관련 규칙 · Read and replace whole files and list directories →결과
The declared result type is Result<(), string>.
효과
실패
Result and effects
링크Create or replace a complete regular file with the UTF-8 encoding of the supplied text.
Related entries
링크Read and replace whole files and list directories
링크Read and replace whole files and list directories
Each function accepts a string path or a Path. Strings use the host path syntax. A Path supplies its normalized relative text. Relative paths use the working directory in an ordinary installed CLI invocation. A package host applies its configured filesystem base and capability policy.
Path and payload arguments are evaluated once in source order before the operation starts. The operation acquires and releases its own resources before returning. It does not change a separately opened File cursor.
Empty paths and paths containing NUL return Err containing a string. Missing read targets, incorrect path kinds, permission denial, package capability denial, and host failures use the same error channel. Errors are values. They do not terminate the program unless the caller chooses to propagate or assert them.
An error string identifies the public operation and the supplied path. It also describes the failure condition. Platform wording, operating system error numbers, and localized explanations are not stable API values.
read returns the entire regular file as text. UTF-8 validity and text preservation follow UTF-8 decoding. Empty files return an empty string. Invalid UTF-8 returns Err without a decoded text value.
read returns every byte in order, including zero bytes and bytes that are not valid UTF-8. Empty files return empty Bytes. Reading does not create or modify the file.
write encodes its string as UTF-8. write writes the supplied bytes unchanged. Both create a missing regular file or replace the full contents of an existing regular file. An empty payload creates or truncates the file to zero bytes. No newline or byte order mark is added.
Writes do not create missing parent directories. They follow the host permission and creation policy. Replacing a file with shorter content removes its previous suffix. Success returns Ok(()) after all payload bytes have been accepted.
A write failure may occur after creation, truncation, or a prefix write. Err does not promise rollback, atomic replacement, or persistence across a system crash. Earlier argument effects remain visible.
list returns immediate children sorted by their exact names in ascending Unicode scalar order. It does not return dot or parent pseudoentries, traverse child directories, normalize Unicode names, or fold case. The name field contains the child name without the parent path.
Each entry kind is exactly file, directory, symlink, or other. Classification uses the entry itself and does not follow a symbolic link. For a regular file, sizeBytes is Some of its byte length when that length fits in int. Other kinds and an unrepresentable size use None().
A name that cannot be represented as Unicode, a failure while reading an entry, or a failure obtaining its metadata returns Err for the whole list. No partial array is returned. Separate operations do not provide a filesystem snapshot, so other processes may change a path between calls.
Host access follows symbolic links where the operation addresses their target, subject to host capability checks. A normalized Path is not an authorization token. Use File when operations must retain one open resource and cursor, and std.fs when the operation concerns complete contents or directory entries.
이유
Exact bytes and strict text decoding keep data conversion explicit. Whole file replacement has a clear effect, and Result makes permission and host failures recoverable. Sorting names makes directory traversal repeatable for a fixed directory state without assuming a host enumeration order.
Replace and create text files with exact content
링크import std.fsimport std.path { Path }import std.testimport std.iolet path = test.assertOk(Path.from("chapter.txt"))test.assertOk(fs.writeText(path, "short\n"))io.writeLine(test.assertOk(fs.readText("chapter.txt")))test.assertOk(fs.writeText("created.txt", "한글"))io.writeLine(test.assertOk(fs.readText("created.txt")))test.assertOk(fs.writeText("created.txt", ""))let text = test.assertOk(fs.readText("created.txt"))let empty = text == ""io.writeLine("empty {empty}")
short
한글
empty true
a much longer old value
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
short한글empty true
Preserve a byte order mark and physical line endings
링크import std.fsimport std.testimport std.ioio.writeLine(test.assertOk(fs.readText("source.txt")))
alpha
한글
alpha한글
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
alpha한글
Preserve raw bytes and reject invalid UTF-8 text
링크import std.fsimport std.bytes { Bytes }import std.testimport std.iolet bytes = test.assertOk(Bytes.fromArray([0, 65, 255]))test.assertOk(fs.writeBytes("data.bin", bytes))io.writeLine(test.assertOk(fs.readBytes("data.bin")).toHex())test.assertErr(fs.readText("data.bin"))io.writeLine("invalid text rejected")test.assertOk(fs.writeBytes("data.bin", Bytes.empty()))io.writeLine(test.assertOk(fs.readBytes("data.bin")).toHex())
0041ff
invalid text rejected
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
0041ffinvalid text rejected
List immediate entries in exact name order
링크import std.fsimport std.testimport std.iolet entries = test.assertOk(fs.list("entries"))for entry in (entries) {let size = match (entry.sizeBytes) {case Some(value) => "{value}"case None() => "none"}io.writeLine("{entry.name} {entry.kind} {size}")}
a.txt file 1
nested directory none
z.txt file 2
zz
a
inside
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
a.txt file 1nested directory nonez.txt file 2
Return recoverable errors for the wrong path kind
링크import std.fsimport std.testimport std.iotest.assertErr(fs.readText("directory"))test.assertErr(fs.readBytes("directory"))test.assertErr(fs.writeText("directory", "text"))test.assertErr(fs.list("plain.txt"))io.writeLine("wrong kinds rejected")
wrong kinds rejected
inside
plain
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
wrong kinds rejected
Evaluate payloads before replacing a file
링크import std.fsimport std.testimport std.iofunction target() -> string {io.writeLine("path")return "source.txt"}function payload() -> string {io.writeLine("text")io.writeLine(test.assertOk(fs.readText("source.txt")))return "new"}test.assertOk(fs.writeText(target(), payload()))io.writeLine(test.assertOk(fs.readText("source.txt")))
path
text
old
new
old
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
pathtextoldnew
Identify the operation and path in a readText error
링크import std.fsimport std.bytes { Bytes }import std.testimport std.iolet error = test.assertErr(fs.readText("missing/item.txt"))let operation = error.contains("readText")let path = error.contains("missing/item.txt")io.writeLine("{operation} {path}")
true true
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
true true
Identify the operation and path in a readBytes error
링크import std.fsimport std.bytes { Bytes }import std.testimport std.iolet error = test.assertErr(fs.readBytes("missing/item.txt"))let operation = error.contains("readBytes")let path = error.contains("missing/item.txt")io.writeLine("{operation} {path}")
true true
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
true true
Identify the operation and path in a writeText error
링크import std.fsimport std.bytes { Bytes }import std.testimport std.iolet error = test.assertErr(fs.writeText("missing/item.txt", "text"))let operation = error.contains("writeText")let path = error.contains("missing/item.txt")io.writeLine("{operation} {path}")
true true
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
true true
Identify the operation and path in a writeBytes error
링크import std.fsimport std.bytes { Bytes }import std.testimport std.iolet error = test.assertErr(fs.writeBytes("missing/item.txt", Bytes.empty()))let operation = error.contains("writeBytes")let path = error.contains("missing/item.txt")io.writeLine("{operation} {path}")
true true
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
true true
Identify the operation and path in a list error
링크import std.fsimport std.bytes { Bytes }import std.testimport std.iolet error = test.assertErr(fs.list("missing/item.txt"))let operation = error.contains("list")let path = error.contains("missing/item.txt")io.writeLine("{operation} {path}")
true true
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
true true