Перейти к содержимому
Топаз6.0 · До релиза
Загрузка →

Поиск в документации

Спецификация 6.0

Выберите результат стрелками и нажмите Enter, чтобы открыть его.

Введите имя API, номер диагностики, правило или тему проекта.

    Библиотека

    std.fs.writeBytes

    Writes bytes to a filesystem path.

    writeBytes(path: string | Path, bytes: Bytes) -> 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.

    readText 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.

    readBytes 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.

    writeText encodes its string as UTF-8. writeBytes 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.

    Результат

    The declared result type is Result<(), string>.

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Create or replace a complete regular file with the supplied bytes unchanged.

    Related entries

    Ссылка

    std.fs →

    Read and replace whole files and list directories

    Ссылка
    Правилоtopaz.stdlib.contract.filesystem.rule

    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.

    readText 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.

    readBytes 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.

    writeText encodes its string as UTF-8. writeBytes 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

    Ссылка
    main.tpzReplace and create text files with exact contentОткрыть песочницу →
    1. import std.fs
    2. import std.path { Path }
    3. import std.test
    4. import std.io
    5. let path = test.assertOk(Path.from("chapter.txt"))
    6. test.assertOk(fs.writeText(path, "short\n"))
    7. io.writeLine(test.assertOk(fs.readText("chapter.txt")))
    8. test.assertOk(fs.writeText("created.txt", "한글"))
    9. io.writeLine(test.assertOk(fs.readText("created.txt")))
    10. test.assertOk(fs.writeText("created.txt", ""))
    11. let text = test.assertOk(fs.readText("created.txt"))
    12. let empty = text == ""
    13. io.writeLine("empty {empty}")
    Ожидаемый выводКод завершения 0
    short
    
    한글
    empty true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    chapter.txtReplace and create text files with exact contentОткрыть песочницу →
    1. a much longer old value
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. short
    2. 한글
    3. empty true

    Preserve a byte order mark and physical line endings

    Ссылка
    main.tpzPreserve a byte order mark and physical line endingsОткрыть песочницу →
    1. import std.fs
    2. import std.test
    3. import std.io
    4. io.writeLine(test.assertOk(fs.readText("source.txt")))
    Ожидаемый выводКод завершения 0
    alpha
    한글
    
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    source.txtPreserve a byte order mark and physical line endingsОткрыть песочницу →
    1. alpha
    2. 한글
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. alpha
    2. 한글

    Preserve raw bytes and reject invalid UTF-8 text

    Ссылка
    main.tpzPreserve raw bytes and reject invalid UTF-8 textОткрыть песочницу →
    1. import std.fs
    2. import std.bytes { Bytes }
    3. import std.test
    4. import std.io
    5. let bytes = test.assertOk(Bytes.fromArray([0, 65, 255]))
    6. test.assertOk(fs.writeBytes("data.bin", bytes))
    7. io.writeLine(test.assertOk(fs.readBytes("data.bin")).toHex())
    8. test.assertErr(fs.readText("data.bin"))
    9. io.writeLine("invalid text rejected")
    10. test.assertOk(fs.writeBytes("data.bin", Bytes.empty()))
    11. io.writeLine(test.assertOk(fs.readBytes("data.bin")).toHex())
    Ожидаемый выводКод завершения 0
    0041ff
    invalid text rejected
    
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 0041ff
    2. invalid text rejected

    List immediate entries in exact name order

    Ссылка
    main.tpzList immediate entries in exact name orderОткрыть песочницу →
    1. import std.fs
    2. import std.test
    3. import std.io
    4. let entries = test.assertOk(fs.list("entries"))
    5. for entry in (entries) {
    6. let size = match (entry.sizeBytes) {
    7. case Some(value) => "{value}"
    8. case None() => "none"
    9. }
    10. io.writeLine("{entry.name} {entry.kind} {size}")
    11. }
    Ожидаемый выводКод завершения 0
    a.txt file 1
    nested directory none
    z.txt file 2
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    entries/z.txtList immediate entries in exact name orderОткрыть песочницу →
    1. zz
    entries/a.txtList immediate entries in exact name orderОткрыть песочницу →
    1. a
    entries/nested/inside.txtList immediate entries in exact name orderОткрыть песочницу →
    1. inside
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. a.txt file 1
    2. nested directory none
    3. z.txt file 2

    Return recoverable errors for the wrong path kind

    Ссылка
    main.tpzReturn recoverable errors for the wrong path kindОткрыть песочницу →
    1. import std.fs
    2. import std.test
    3. import std.io
    4. test.assertErr(fs.readText("directory"))
    5. test.assertErr(fs.readBytes("directory"))
    6. test.assertErr(fs.writeText("directory", "text"))
    7. test.assertErr(fs.list("plain.txt"))
    8. io.writeLine("wrong kinds rejected")
    Ожидаемый выводКод завершения 0
    wrong kinds rejected
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    directory/inside.txtReturn recoverable errors for the wrong path kindОткрыть песочницу →
    1. inside
    plain.txtReturn recoverable errors for the wrong path kindОткрыть песочницу →
    1. plain
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. wrong kinds rejected

    Evaluate payloads before replacing a file

    Ссылка
    main.tpzEvaluate payloads before replacing a fileОткрыть песочницу →
    1. import std.fs
    2. import std.test
    3. import std.io
    4. function target() -> string {
    5. io.writeLine("path")
    6. return "source.txt"
    7. }
    8. function payload() -> string {
    9. io.writeLine("text")
    10. io.writeLine(test.assertOk(fs.readText("source.txt")))
    11. return "new"
    12. }
    13. test.assertOk(fs.writeText(target(), payload()))
    14. io.writeLine(test.assertOk(fs.readText("source.txt")))
    Ожидаемый выводКод завершения 0
    path
    text
    old
    new
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    source.txtEvaluate payloads before replacing a fileОткрыть песочницу →
    1. old
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. path
    2. text
    3. old
    4. new

    Identify the operation and path in a readText error

    Ссылка
    main.tpzIdentify the operation and path in a readText errorОткрыть песочницу →
    1. import std.fs
    2. import std.bytes { Bytes }
    3. import std.test
    4. import std.io
    5. let error = test.assertErr(fs.readText("missing/item.txt"))
    6. let operation = error.contains("readText")
    7. let path = error.contains("missing/item.txt")
    8. io.writeLine("{operation} {path}")
    Ожидаемый выводКод завершения 0
    true true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. true true

    Identify the operation and path in a readBytes error

    Ссылка
    main.tpzIdentify the operation and path in a readBytes errorОткрыть песочницу →
    1. import std.fs
    2. import std.bytes { Bytes }
    3. import std.test
    4. import std.io
    5. let error = test.assertErr(fs.readBytes("missing/item.txt"))
    6. let operation = error.contains("readBytes")
    7. let path = error.contains("missing/item.txt")
    8. io.writeLine("{operation} {path}")
    Ожидаемый выводКод завершения 0
    true true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. true true

    Identify the operation and path in a writeText error

    Ссылка
    main.tpzIdentify the operation and path in a writeText errorОткрыть песочницу →
    1. import std.fs
    2. import std.bytes { Bytes }
    3. import std.test
    4. import std.io
    5. let error = test.assertErr(fs.writeText("missing/item.txt", "text"))
    6. let operation = error.contains("writeText")
    7. let path = error.contains("missing/item.txt")
    8. io.writeLine("{operation} {path}")
    Ожидаемый выводКод завершения 0
    true true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. true true

    Identify the operation and path in a writeBytes error

    Ссылка
    main.tpzIdentify the operation and path in a writeBytes errorОткрыть песочницу →
    1. import std.fs
    2. import std.bytes { Bytes }
    3. import std.test
    4. import std.io
    5. let error = test.assertErr(fs.writeBytes("missing/item.txt", Bytes.empty()))
    6. let operation = error.contains("writeBytes")
    7. let path = error.contains("missing/item.txt")
    8. io.writeLine("{operation} {path}")
    Ожидаемый выводКод завершения 0
    true true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. true true

    Identify the operation and path in a list error

    Ссылка
    main.tpzIdentify the operation and path in a list errorОткрыть песочницу →
    1. import std.fs
    2. import std.bytes { Bytes }
    3. import std.test
    4. import std.io
    5. let error = test.assertErr(fs.list("missing/item.txt"))
    6. let operation = error.contains("list")
    7. let path = error.contains("missing/item.txt")
    8. io.writeLine("{operation} {path}")
    Ожидаемый выводКод завершения 0
    true true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. true true

    Меню

    Загрузка →