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

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

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

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

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

    Библиотека · std.io

    File.write

    Writes text through this File resource.

    write(s: string) -> Result<(), string>
    Модуль
    std.io →
    Получатель
    File
    Минимальное число аргументов
    1
    Максимальное число аргументов
    1

    Declaration and parameters

    Ссылка

    Доступность

    Включено по умолчанию · Не определено

    Import std.io in language mode 5.21.

    The current compiler selects std/io.tpz for this language mode. Availability in other released editions and inclusion in each installed distribution are Pending.

    Получатель

    File

    Ограничения параметров

    open evaluates its path once and opens an existing regular file for reading and writing. It does not create or truncate a file. A successful result is Ok containing a File with the cursor at the first byte.

    String paths use the host path syntax. Relative paths resolve against the working directory for an ordinary installed CLI invocation. A package host applies its configured filesystem base and capability policy. NUL, an empty path, a missing file, a directory, and denied read or write access return Err containing an error string.

    An open error follows the filesystem error context contract with open as the public operation. An error result does not grant a handle, and path validation does not bypass operating system or package permissions.

    File values refer to a resource identity. Copies share the open state and cursor. The handle continues to identify the opened file when the directory entry is renamed or replaced. This is the host resource exception in collection value semantics.

    read consumes the remaining bytes from the shared cursor through EOF. UTF-8 validity and text preservation follow UTF-8 decoding. A successful read returns Ok containing text, and a successful read at EOF returns an empty string.

    A read error returns Err containing an error string without a text value. Bytes already consumed before a host or decoding error are not restored. Callers must not assume the previous cursor position after a read error.

    write encodes its string as UTF-8 and writes all bytes at the shared cursor. It adds no newline. Success advances the cursor by the encoded byte count, overwrites those bytes, and preserves an existing suffix beyond them. A write at EOF extends the file.

    An empty write succeeds without moving the cursor. A closed handle, denied access, or host write failure returns Err. A host failure may leave a written prefix and an advanced cursor. It does not roll back earlier argument effects or file changes.

    close returns unit, releases the resource, and marks every alias closed. Closing an already closed resource also returns unit. A later read or write through any alias returns Err. A host failure while closing produces a structured runtime fault at the close call.

    The Topaz 6.0 host close fault is TPZ4009. Its primary location is the close call. A successful write or close does not promise persistence across a system crash.

    Receiver and argument expressions are evaluated once in source order before each resource operation. Use std.fs for whole file replacement or whole file reads. Use File when successive operations must share a cursor and lifetime.

    Результат

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

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Write UTF-8 bytes at the shared cursor without adding a newline or removing a later suffix. Return a recoverable error on failure.

    Related entries

    Ссылка

    std.io →

    Use a file handle with a shared cursor

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

    Use a file handle with a shared cursor

    open evaluates its path once and opens an existing regular file for reading and writing. It does not create or truncate a file. A successful result is Ok containing a File with the cursor at the first byte.

    String paths use the host path syntax. Relative paths resolve against the working directory for an ordinary installed CLI invocation. A package host applies its configured filesystem base and capability policy. NUL, an empty path, a missing file, a directory, and denied read or write access return Err containing an error string.

    An open error follows the filesystem error context contract with open as the public operation. An error result does not grant a handle, and path validation does not bypass operating system or package permissions.

    File values refer to a resource identity. Copies share the open state and cursor. The handle continues to identify the opened file when the directory entry is renamed or replaced. This is the host resource exception in collection value semantics.

    read consumes the remaining bytes from the shared cursor through EOF. UTF-8 validity and text preservation follow UTF-8 decoding. A successful read returns Ok containing text, and a successful read at EOF returns an empty string.

    A read error returns Err containing an error string without a text value. Bytes already consumed before a host or decoding error are not restored. Callers must not assume the previous cursor position after a read error.

    write encodes its string as UTF-8 and writes all bytes at the shared cursor. It adds no newline. Success advances the cursor by the encoded byte count, overwrites those bytes, and preserves an existing suffix beyond them. A write at EOF extends the file.

    An empty write succeeds without moving the cursor. A closed handle, denied access, or host write failure returns Err. A host failure may leave a written prefix and an advanced cursor. It does not roll back earlier argument effects or file changes.

    close returns unit, releases the resource, and marks every alias closed. Closing an already closed resource also returns unit. A later read or write through any alias returns Err. A host failure while closing produces a structured runtime fault at the close call.

    The Topaz 6.0 host close fault is TPZ4009. Its primary location is the close call. A successful write or close does not promise persistence across a system crash.

    Receiver and argument expressions are evaluated once in source order before each resource operation. Use std.fs for whole file replacement or whole file reads. Use File when successive operations must share a cursor and lifetime.

    Причина

    A handle gives successive operations one cursor and one lifetime. Whole file operations already belong to std.fs, so rereading and replacing by path would duplicate their meaning. An existing file open avoids surprising creation or truncation, and recoverable access failures stay in Result.

    Open and close an existing file without changing its bytes

    Ссылка
    main.tpzOpen and close an existing file without changing its bytesОткрыть песочницу →
    1. import std.io
    2. import std.fs
    3. import std.test
    4. let file = test.assertOk(io.open("source.txt"))
    5. file.close()
    6. io.writeLine(test.assertOk(fs.readText("source.txt")))
    7. let missing = test.assertErr(io.open("missing.txt"))
    8. let named = missing.contains("missing.txt")
    9. io.writeLine("missing {named}")
    Ожидаемый выводКод завершения 0
    original
    missing true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    source.txtOpen and close an existing file without changing its bytesОткрыть песочницу →
    1. original
    Ожидаемый результат

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

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

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

    Reject a directory when opening a file

    Ссылка
    main.tpzReject a directory when opening a fileОткрыть песочницу →
    1. import std.io
    2. match (io.open(".")) {
    3. case Err(_) => io.writeLine("directory rejected")
    4. case Ok(file) => {
    5. file.close()
    6. io.writeLine("directory accepted")
    7. }
    8. }
    Ожидаемый выводКод завершения 0
    directory rejected
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

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

    Share the cursor across file aliases

    Ссылка
    main.tpzShare the cursor across file aliasesОткрыть песочницу →
    1. import std.io
    2. import std.test
    3. let file = test.assertOk(io.open("source.txt"))
    4. let alias = file
    5. io.writeLine(test.assertOk(file.read()))
    6. let tail = test.assertOk(alias.read())
    7. let atEnd = tail == ""
    8. io.writeLine("{atEnd}")
    9. alias.close()
    Ожидаемый выводКод завершения 0
    alpha
    true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    source.txtShare the cursor across file aliasesОткрыть песочницу →
    1. alpha
    Ожидаемый результат

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

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

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

    Write at the cursor and retain the rest of the file

    Ссылка
    main.tpzWrite at the cursor and retain the rest of the fileОткрыть песочницу →
    1. import std.io
    2. import std.fs
    3. import std.test
    4. let file = test.assertOk(io.open("source.txt"))
    5. test.assertOk(file.write("XY"))
    6. let tail = test.assertOk(file.read())
    7. io.writeLine("tail {tail}")
    8. file.close()
    9. let whole = test.assertOk(fs.readText("source.txt"))
    10. io.writeLine("whole {whole}")
    Ожидаемый выводКод завершения 0
    tail cdef
    whole XYcdef
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    source.txtWrite at the cursor and retain the rest of the fileОткрыть песочницу →
    1. abcdef
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. tail cdef
    2. whole XYcdef

    Extend a file after reading through EOF

    Ссылка
    main.tpzExtend a file after reading through EOFОткрыть песочницу →
    1. import std.io
    2. import std.fs
    3. import std.test
    4. let file = test.assertOk(io.open("source.txt"))
    5. test.assertOk(file.read())
    6. test.assertOk(file.write("β"))
    7. file.close()
    8. io.writeLine(test.assertOk(fs.readText("source.txt")))
    Ожидаемый выводКод завершения 0
    alphaβ
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    source.txtExtend a file after reading through EOFОткрыть песочницу →
    1. alpha
    Ожидаемый результат

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

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

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

    Close every alias and reject later access

    Ссылка
    main.tpzClose every alias and reject later accessОткрыть песочницу →
    1. import std.io
    2. import std.fs
    3. import std.test
    4. let file = test.assertOk(io.open("source.txt"))
    5. let alias = file
    6. file.close()
    7. alias.close()
    8. test.assertErr(alias.read())
    9. io.writeLine("read rejected")
    10. test.assertErr(alias.write("changed"))
    11. io.writeLine("write rejected")
    12. io.writeLine(test.assertOk(fs.readText("source.txt")))
    Ожидаемый выводКод завершения 0
    read rejected
    write rejected
    original
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    source.txtClose every alias and reject later accessОткрыть песочницу →
    1. original
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. read rejected
    2. write rejected
    3. original

    Return a file read error for invalid UTF-8

    Ссылка
    main.tpzReturn a file read error for invalid UTF-8Открыть песочницу →
    1. import std.io
    2. import std.fs
    3. import std.bytes { Bytes }
    4. import std.test
    5. let invalid = test.assertOk(Bytes.fromArray([255]))
    6. test.assertOk(fs.writeBytes("invalid.txt", invalid))
    7. let file = test.assertOk(io.open("invalid.txt"))
    8. test.assertErr(file.read())
    9. file.close()
    10. io.writeLine("invalid text rejected")
    Ожидаемый выводКод завершения 0
    invalid text rejected
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

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

    Меню

    Загрузка →