IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

FileDescriptor

struct FileDescriptor

Owning file descriptor that is closed explicitly with close().

Movable but not copyable, so exactly one value owns the descriptor. -1 is the niche, so Optional[FileDescriptor] is the size of a descriptor.

Examples:

from std.io import FileDescriptor

def write_greeting(var fd: FileDescriptor) raises:
fd.write_string("hello\n")
fd^.close()

Implemented traits​

AnyType, Movable, UnsafeNicheable, UnsafeSingleNicheable, Writer

Methods​

__init__​

def __init__(out self, *, unsafe_raw_fd: RawFileDescriptor)

Takes ownership of a raw file descriptor.

Args:

  • ​unsafe_raw_fd (RawFileDescriptor): The descriptor to own. Nothing else may close it, so never pass stdin, stdout, stderr or the descriptor behind a FileHandle.

close​

def close(deinit self)

Closes the owned file descriptor.

Raises:

If the close fails. A failed close can mean buffered writes never reached the file.

write_bytes​

def write_bytes(mut self, bytes: Span[UInt8]) -> Int

Writes at most len(bytes) bytes to the file.

A single call may write fewer bytes than requested. Use write_bytes_exact() to write the whole span.

Args:

Returns:

Int: The number of bytes written.

Raises:

If the write fails.

write_bytes_exact​

def write_bytes_exact(mut self, bytes: Span[UInt8])

Writes all of bytes to the file.

Args:

Raises:

If a write fails before every byte is written.

write_string​

def write_string(mut self, string: StringSpan)

Writes a string to the file.

Writer requires this method to be non-raising; use write_bytes_exact() to observe write errors.

Args:

read_bytes​

def read_bytes(mut self, buffer: Span[UInt8]) -> Int

Reads at most len(buffer) bytes into buffer.

A single call may read fewer bytes than requested. A return value of 0 means the end of the file was reached.

Args:

  • ​buffer (Span[UInt8]): The buffer to read bytes into.

Returns:

Int: The number of bytes read.

Raises:

If the read fails.