FileHandle

public final class FileHandle : FileDescriptor

A FileHandle is a handle to an open file.

When creating a FileHandle it takes ownership of the underlying file descriptor. When a FileHandle is no longer needed you must close it or take back ownership of the file descriptor using takeDescriptorOwnership.

Note

One underlying file descriptor should usually be managed by one FileHandle only.

Warning

Failing to manage the lifetime of a FileHandle correctly will result in undefined behaviour.

Warning

FileHandle objects are not thread-safe and are mutable. They also cannot be fully thread-safe as they refer to a global underlying file descriptor.

  • Declaration

    Swift

    public private(set) var isOpen: Bool
  • Create a FileHandle taking ownership of descriptor. You must call FileHandle.close or FileHandle.takeDescriptorOwnership before this object can be safely released.

    Declaration

    Swift

    public init(descriptor: CInt)
  • Duplicates this FileHandle. This means that a new FileHandle object with a new underlying file descriptor is returned. The caller takes ownership of the returned FileHandle and is responsible for closing it.

    Warning

    The returned FileHandle is not fully independent, the seek pointer is shared as documented by dup(2).

    Declaration

    Swift

    public func duplicate() throws -> FileHandle

    Return Value

    A new FileHandle with a fresh underlying file descriptor but shared seek pointer.

  • Take the ownership of the underlying file descriptor. This is similar to close() but the underlying file descriptor remains open. The caller is responsible for closing the file descriptor by some other means.

    After calling this, the FileHandle cannot be used for anything else and all the operations will throw.

    Declaration

    Swift

    public func takeDescriptorOwnership() throws -> CInt

    Return Value

    The underlying file descriptor, now owned by the caller.

  • Declaration

    Swift

    public func close() throws
  • Declaration

    Swift

    public func withUnsafeFileDescriptor<T>(_ body: (CInt) throws -> T) throws -> T
  • Open a new FileHandle.

    Declaration

    Swift

    public convenience init(path: String) throws

    Parameters

    path

    the path of the file to open. The ownership of the file descriptor is transferred to this FileHandle and so it will be closed once close is called.