iOS Developer Library

Developer

Foundation Framework Reference NSFileHandle Class Reference

Options
Deployment Target:

On This Page
Language:

NSFileHandle

Inherits From


Conforms To


Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in iOS 2.0 and later

The NSFileHandle class is an object-oriented wrapper for a file descriptor. 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 NSFileHandle 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 file handle object itself is deallocated. If you want to use a file handle object with a file descriptor that you created, use the initWithFileDescriptor: method or use the initWithFileDescriptor:closeOnDealloc: method and pass NOfalse 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 have configured a run loop and are using it to process events.

For more information about configuring and using run loops, see Threading Programming Guide.

  • Returns a file handle initialized for reading the file, device, or named socket at the specified path.

    Declaration

    Swift

    convenience init?(forReadingAtPath path: String)

    Objective-C

    + (instancetype)fileHandleForReadingAtPath:(NSString *)path

    Parameters

    path

    The path to the file, device, or named socket to access.

    Return Value

    The initialized file handle object or nil if no file exists at path.

    Discussion

    The file pointer is set to the beginning of the file. You cannot write data to the returned file handle object. Use the readDataToEndOfFile or readDataOfLength: methods to read data from it.

    When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Returns a file handle initialized for reading the file, device, or named socket at the specified URL.

    Declaration

    Swift

    convenience init?(forReadingFromURL url: NSURL, error error: NSErrorPointer)

    Objective-C

    + (instancetype)fileHandleForReadingFromURL:(NSURL *)url error:(NSError **)error

    Parameters

    url

    The URL of the file, device, or named socket to access.

    error

    If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

    Return Value

    The initialized file handle object or nil if no file exists at url.

    Discussion

    The file pointer is set to the beginning of the file. You cannot write data to the returned file handle object. Use the readDataToEndOfFile or readDataOfLength: methods to read data from it.

    When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later

  • Returns a file handle initialized for writing to the file, device, or named socket at the specified path.

    Declaration

    Swift

    convenience init?(forWritingAtPath path: String)

    Objective-C

    + (instancetype)fileHandleForWritingAtPath:(NSString *)path

    Parameters

    path

    The path to the file, device, or named socket to access.

    Return Value

    The initialized file handle object or nil if no file exists at path.

    Discussion

    The file pointer is set to the beginning of the file. You cannot read data from the returned file handle object. Use the writeData: method to write data to the file handle.

    When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Returns a file handle initialized for writing to the file, device, or named socket at the specified URL.

    Declaration

    Swift

    convenience init?(forWritingToURL url: NSURL, error error: NSErrorPointer)

    Objective-C

    + (instancetype)fileHandleForWritingToURL:(NSURL *)url error:(NSError **)error

    Parameters

    url

    The URL of the file, device, or named socket to access.

    error

    If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

    Return Value

    The initialized file handle object or nil if no file exists at url.

    Discussion

    The file pointer is set to the beginning of the file. The returned object responds only to writeData:.

    When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later

  • Returns a file handle initialized for reading and writing to the file, device, or named socket at the specified path.

    Declaration

    Swift

    convenience init?(forUpdatingAtPath path: String)

    Objective-C

    + (instancetype)fileHandleForUpdatingAtPath:(NSString *)path

    Parameters

    path

    The path to the file, device, or named socket to access.

    Return Value

    The initialized file handle object or nil if no file exists at path.

    Discussion

    The file pointer is set to the beginning of the file. The returned object responds to both read... messages and writeData:.

    When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Returns a file handle initialized for reading and writing to the file, device, or named socket at the specified URL.

    Declaration

    Swift

    convenience init?(forUpdatingURL url: NSURL, error error: NSErrorPointer)

    Objective-C

    + (instancetype)fileHandleForUpdatingURL:(NSURL *)url error:(NSError **)error

    Parameters

    url

    The URL of the file, device, or named socket to access.

    error

    If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

    Return Value

    The initialized file handle object or nil if no file exists at url.

    Discussion

    The file pointer is set to the beginning of the file. The returned object responds to both NSFileHandleread... messages and writeData:.

    When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later

  • Returns the file handle associated with the standard error file.

    Declaration

    Swift

    class func fileHandleWithStandardError() -> NSFileHandle

    Objective-C

    + (NSFileHandle *)fileHandleWithStandardError

    Return Value

    The shared file handle associated with the standard error file.

    Discussion

    Conventionally this is a terminal device to which error messages are sent. There is one standard error file handle per process; it is a shared instance.

    When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Returns the file handle associated with the standard input file.

    Declaration

    Swift

    class func fileHandleWithStandardInput() -> NSFileHandle

    Objective-C

    + (NSFileHandle *)fileHandleWithStandardInput

    Return Value

    The shared file handle associated with the standard input file.

    Discussion

    Conventionally this is a terminal device on which the user enters a stream of data. There is one standard input file handle per process; it is a shared instance.

    When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Returns the file handle associated with the standard output file.

    Declaration

    Swift

    class func fileHandleWithStandardOutput() -> NSFileHandle

    Objective-C

    + (NSFileHandle *)fileHandleWithStandardOutput

    Return Value

    The shared file handle associated with the standard output file.

    Discussion

    Conventionally this is a terminal device that receives a stream of data from a program. There is one standard output file handle per process; it is a shared instance.

    When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Returns a file handle associated with a null device.

    Declaration

    Swift

    class func fileHandleWithNullDevice() -> NSFileHandle

    Objective-C

    + (NSFileHandle *)fileHandleWithNullDevice

    Return Value

    A file handle associated with a null device.

    Discussion

    You can use null-device file handles as “placeholders” for standard-device file handles or in collection objects to avoid exceptions and other errors resulting from messages being sent to invalid file handles. Read messages sent to a null-device file handle return an end-of-file indicator (an empty NSData object) rather than raise an exception. Write messages are no-ops, whereas fileDescriptor returns an illegal value. Other methods are no-ops or return “sensible” values.

    When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Initializes and returns a file handle object associated with the specified file descriptor.

    Declaration

    Swift

    convenience init(fileDescriptor fileDescriptor: Int32)

    Objective-C

    - (instancetype)initWithFileDescriptor:(int)fileDescriptor

    Parameters

    fileDescriptor

    The POSIX file descriptor with which to initialize the file handle. This descriptor represents an open file or socket that you created previously. For example, when creating a file handle for a socket, you would pass the value returned by the socket function.

    Return Value

    A file handle initialized with fileDescriptor.

    Discussion

    The file descriptor you pass in to this method is not owned by the file handle object. Therefore, you are responsible for closing the file descriptor at some point after disposing of the file handle object.

    You can create a file handle for a socket by using the result of a socket call as fileDescriptor.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

    See Also

    – closeFile

  • Initializes and returns a file handle object associated with the specified file descriptor and deallocation policy.

    Declaration

    Swift

    init(fileDescriptor fileDescriptor: Int32, closeOnDealloc flag: Bool)

    Objective-C

    - (instancetype)initWithFileDescriptor:(int)fileDescriptor closeOnDealloc:(BOOL)flag

    Parameters

    fileDescriptor

    The POSIX file descriptor with which to initialize the file handle.

    flag

    YEStrue if the returned file handle object should take ownership of the file descriptor and close it for you or NOfalse if you want to maintain ownership of the file descriptor.

    Return Value

    An initialized file handle object.

    Special Considerations

    If flag is NOfalse, the file descriptor you pass in to this method is not owned by the file handle object. In such a case, you are responsible for closing the file descriptor at some point after disposing of the file handle object. If you want the file handle object to close the descriptor for you automatically, pass YEStrue for the flag parameter.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

    See Also

    – closeFile

  • The POSIX file descriptor associated with the receiver. (read-only)

    Declaration

    Swift

    var fileDescriptor: Int32 { get }

    Objective-C

    @property(readonly) int fileDescriptor

    Discussion

    You can use this method to retrieve the file descriptor while it is open. If the file handle object owns the file descriptor, you must not close it yourself. However, you can use the closeFile method to close the file descriptor programmatically. If you do call the closeFile method, subsequent calls to this method raise an exception.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • The data currently available in the receiver. (read-only)

    Declaration

    Swift

    @NSCopying var availableData: NSData { get }

    Objective-C

    @property(readonly, copy) NSData *availableData

    Discussion

    The data currently available through the receiver, up to the the maximum size that can be represented by an NSData object.

    If the receiver is a file, this method returns the data obtained by reading the file from the current file pointer to the end of the file. If the receiver is a communications channel, this method reads up to a buffer of data and returns it; if no data is available, the method blocks. Returns an empty data object if the end of file is reached. This method raises NSFileHandleOperationException if attempts to determine the file-handle type fail or if attempts to read from the file or channel fail.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Synchronously reads the available data up to the end of file or maximum number of bytes.

    Declaration

    Swift

    func readDataToEndOfFile() -> NSData

    Objective-C

    - (NSData *)readDataToEndOfFile

    Return Value

    The data available through the receiver up to maximum size that can be represented by an NSData object or, if a communications channel, until an end-of-file indicator is returned.

    Discussion

    This method invokes readDataOfLength: as part of its implementation.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Synchronously reads data up to the specified number of bytes.

    Declaration

    Swift

    func readDataOfLength(_ length: Int) -> NSData

    Objective-C

    - (NSData *)readDataOfLength:(NSUInteger)length

    Parameters

    length

    The number of bytes to read from the receiver.

    Return Value

    The data available through the receiver up to a maximum of length bytes, or the maximum size that can be represented by an NSData object, whichever is the smaller.

    Discussion

    If the receiver is a file, this method returns the data obtained by reading length bytes starting at the current file pointer. If length bytes are not available, this method returns the data from the current file pointer to the end of the file. If the receiver is a communications channel, the method reads up to length bytes from the channel. Returns an empty NSData object if the file is positioned at the end of the file or if an end-of-file indicator is returned on a communications channel. This method raises NSFileHandleOperationException if attempts to determine the file-handle type fail or if attempts to read from the file or channel fail.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Synchronously writes the specified data to the receiver.

    Declaration

    Swift

    func writeData(_ data: NSData)

    Objective-C

    - (void)writeData:(NSData *)data

    Parameters

    data

    The data to be written.

    Discussion

    If the receiver is a file, writing takes place at the file pointer’s current position. After it writes the data, the method advances the file pointer by the number of bytes written. This method raises an exception if the file descriptor is closed or is not valid, if the receiver represents an unconnected pipe or socket endpoint, if no free space is left on the file system, or if any other writing error occurs.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • The block to use for reading the contents of the file handle asynchronously.

    Declaration

    Swift

    var readabilityHandler: ((NSFileHandle!) -> Void)?

    Objective-C

    @property(copy) void (^readabilityHandler)( NSFileHandle *)

    Discussion

    The default value of this property is nil. Assigning a valid block object to this property creates a dispatch source for reading the contents of the file or socket. Your block is submitted to the file handle’s dispatch queue when there is data to read. When reading a file, your handler block is typically executed repeatedly until the entire contents of the file have been read. When reading data from a socket, your handler block is executed whenever there is data on the socket waiting to be read.

    The block you provide must accept a single parameter that is the current file handle. The return type of your block should be void.

    To stop reading the file or socket, set the value of this property to nil. Doing so cancels the dispatch source and cleans up the file handle’s structures appropriately.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later

  • The block to use for writing the contents of the file handle asynchronously.

    Declaration

    Swift

    var writeabilityHandler: ((NSFileHandle!) -> Void)?

    Objective-C

    @property(copy) void (^writeabilityHandler)( NSFileHandle *)

    Discussion

    The default value of this property is nil. Assigning a valid block object to this property creates a dispatch source for writing the contents of the file or socket. Your block is submitted to the file handle’s dispatch queue when there is room available to write more data. When writing a file, your handler block is typically executed repeatedly until the entire contents of the file have been written. When writing data to a socket, your handler block is executed whenever the socket is ready to accept more data.

    The block you provide must accept a single parameter that is the current file handle. The return type of your block should be void.

    To stop writing data to the file or socket, set the value of this property to nil. Doing so cancels the dispatch source and cleans up the file handle’s structures appropriately.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 5.0 and later

  • The position of the file pointer within the file represented by the receiver. (read-only)

    Declaration

    Swift

    var offsetInFile: UInt64 { get }

    Objective-C

    @property(readonly) unsigned long long offsetInFile

    Special Considerations

    Raises an exception if the message is sent to a file handle representing a pipe or socket or if the file descriptor is closed.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Puts the file pointer at the end of the file referenced by the receiver and returns the new file offset.

    Declaration

    Swift

    func seekToEndOfFile() -> UInt64

    Objective-C

    - (unsigned long long)seekToEndOfFile

    Return Value

    The file offset with the file pointer at the end of the file. This is therefore equal to the size of the file.

    Special Considerations

    Raises an exception if the message is sent to an NSFileHandle object representing a pipe or socket or if the file descriptor is closed.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Moves the file pointer to the specified offset within the file represented by the receiver.

    Declaration

    Swift

    func seekToFileOffset(_ offset: UInt64)

    Objective-C

    - (void)seekToFileOffset:(unsigned long long)offset

    Parameters

    offset

    The offset to seek to.

    Special Considerations

    Raises an exception if the message is sent to an NSFileHandle object representing a pipe or socket, if the file descriptor is closed, or if any other error occurs in seeking.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Disallows further access to the represented file or communications channel and signals end of file on communications channels that permit writing.

    Declaration

    Swift

    func closeFile()

    Objective-C

    - (void)closeFile

    Discussion

    If the file handle object owns its file descriptor, it automatically closes that descriptor when it is deallocated. If you initialized the file handle object using the initWithFileDescriptor: method, or you initialized it using the initWithFileDescriptor:closeOnDealloc: and passed NOfalse for the flag parameter, you can use this method to close the file descriptor; otherwise, you must close the file descriptor yourself.

    After calling this method, you may still use the file handle object but must not attempt to read or write data or use the object to operate on the file descriptor. Attempts to read or write a closed file descriptor raise an exception.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Causes all in-memory data and attributes of the file represented by the receiver to be written to permanent storage.

    Declaration

    Swift

    func synchronizeFile()

    Objective-C

    - (void)synchronizeFile

    Discussion

    This method should be invoked by programs that require the file to always be in a known state. An invocation of this method does not return until memory is flushed.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Truncates or extends the file represented by the receiver to a specified offset within the file and puts the file pointer at that position.

    Declaration

    Swift

    func truncateFileAtOffset(_ offset: UInt64)

    Objective-C

    - (void)truncateFileAtOffset:(unsigned long long)offset

    Parameters

    offset

    The offset within the file that will mark the new end of the file.

    Discussion

    If the file is extended (if offset is beyond the current end of file), the added characters are null bytes.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Strings that are used as keys in a userinfo dictionary in a file handle notification.

    Declaration

    Swift

    let NSFileHandleNotificationFileHandleItem: String let NSFileHandleNotificationDataItem: String

    Objective-C

    NSString * const NSFileHandleNotificationFileHandleItem; NSString * const NSFileHandleNotificationDataItem;

    Constants

    • NSFileHandleNotificationFileHandleItem

      NSFileHandleNotificationFileHandleItem

      A key in the userinfo dictionary in a NSFileHandleConnectionAcceptedNotification notification.

      The corresponding value is the NSFileHandle object representing the “near” end of a socket connection.

      Available in iOS 2.0 and later

    • NSFileHandleNotificationDataItem

      NSFileHandleNotificationDataItem

      A key in the userinfo dictionary in a NSFileHandleReadCompletionNotification and NSFileHandleReadToEndOfFileCompletionNotification.

      The corresponding value is an NSData object containing the available data read from a socket connection.

      Available in iOS 2.0 and later

  • Constant that defines the name of a file operation exception.

    Declaration

    Swift

    let NSFileHandleOperationException: String

    Objective-C

    extern NSString *NSFileHandleOperationException;

    Constants

    • NSFileHandleOperationException

      NSFileHandleOperationException

      Raised by NSFileHandle if attempts to determine file-handle type fail or if attempts to read from a file or channel fail.

      Available in iOS 2.0 and later

  • Constant that is currently unused.

    Declaration

    Objective-C

    NSString * const NSFileHandleNotificationMonitorModes;

    Constants

    • NSFileHandleNotificationMonitorModes

      NSFileHandleNotificationMonitorModes

      Currently unused.

      Available in iOS 2.0 and later

      Deprecated in iOS 5.0

  • This notification is posted when an NSFileHandle object establishes a socket connection between two processes, creates an NSFileHandle object for one end of the connection, and makes this object available to observers by putting it in the userInfo dictionary. To cause the posting of this notification, you must send either acceptConnectionInBackgroundAndNotify or acceptConnectionInBackgroundAndNotifyForModes: to an NSFileHandle object representing a server stream-type socket.

    The notification object is the NSFileHandle object that sent the notification. The userInfo dictionary contains the following information:

    Key

    Value

    NSFileHandleNotificationFileHandleItem

    The NSFileHandle object representing the “near” end of a socket connection

    @"NSFileHandleError"

    An NSNumber object containing an integer representing the UNIX-type error which occurred

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • This notification is posted when the file handle determines that data is currently available for reading in a file or at a communications channel. The observers can then issue the appropriate messages to begin reading the data. To cause the posting of this notification, you must send either waitForDataInBackgroundAndNotify or waitForDataInBackgroundAndNotifyForModes: to an appropriate NSFileHandle object.

    The notification object is the NSFileHandle object that sent the notification. This notification does not contain a userInfo dictionary.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • This notification is posted when the file handle reads the data currently available in a file or at a communications channel. It makes the data available to observers by putting it in the userInfo dictionary. To cause the posting of this notification, you must send either readInBackgroundAndNotify or readInBackgroundAndNotifyForModes: to an appropriate NSFileHandle object.

    The notification object is the NSFileHandle object that sent the notification. The userInfo dictionary contains the following information:

    Key

    Value

    NSFileHandleNotificationDataItem

    An NSData object containing the available data read from a socket connection

    @"NSFileHandleError"

    An NSNumber object containing an integer representing the UNIX-type error which occurred

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • This notification is posted when the file handle reads all data in the file or, if a communications channel, until the other process signals the end of data. It makes the data available to observers by putting it in the userInfo dictionary. To cause the posting of this notification, you must send either readToEndOfFileInBackgroundAndNotify or readToEndOfFileInBackgroundAndNotifyForModes: to an appropriate NSFileHandle object.

    The notification object is the NSFileHandle object that sent the notification. The userInfo dictionary contains the following information:

    Key

    Value

    NSFileHandleNotificationDataItem

    An NSData object containing the available data read from a socket connection

    @"NSFileHandleError"

    An NSNumber object containing an integer representing the UNIX-type error which occurred

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later