Contents

FileHandle

An object-oriented wrapper for a file descriptor.

Declaration

class FileHandle

Mentioned in

Overview

You use file handle objects to access data associated with files, sockets, pipes, and devices. For files, you can read, write, and seek within the file. For sockets, pipes, and devices, you can use a file handle object to monitor the device and process data asynchronously.

Most creation methods for FileHandle cause the file handle object to take ownership of the associated file descriptor. This means that the file handle object both creates the file descriptor and is responsible for closing it later, usually when the system deallocates the file handle object. If you want to use a file handle object with a file descriptor that you created, use the init(fileDescriptor:) method or use the init(fileDescriptor:closeOnDealloc:) method and pass false for the flag parameter.

Run Loop Considerations

When using a file handle object to communicate asynchronously with a socket, you must initiate the corresponding operations from a thread with an active run loop. Although the read, accept, and wait operations themselves are performed asynchronously on background threads, the file handle uses a run loop source to monitor the operations and notify your code appropriately. Therefore, you must call those methods from your application’s main thread or from any thread where you’ve configured a run loop and are using it to process events.

Topics

Creating a File Handle

Getting a File Handle

Getting a File Descriptor

Reading from a File Handle Asynchronously

Reading from a File Handle Synchronously

Reading Asynchronously with Notifications

Writing to a File Handle

Seeking Within a File

Operating on a File

Monitoring for Readability and Writability

Constants

Notifications

Deprecated

Structures

Initializers

Default Implementations

See Also

Managed file access