# NSFileHandle class reference

richard@brainstorm.co.uk
Generated at 2025-09-10 09:16:48 +0000
1997 Free Software Foundation, Inc.
Software documentation for the NSFileHandle class
Foundation/NSFileHandle.h

`NSFileHandle` is a class that provides a wrapper for accessing system files and socket connections. You can open connections to a file using class methods such as +fileHandleForReadingAtPath: .

GNUstep extends the use of this class to allow you to create network connections (sockets), secure connections and also allows you to use compression with these files and connections (as long as GNUstep Base was compiled with the zlib library).

fileHandleForReadingAtPath:
path
Returns an `NSFileHandle` object set up for reading from the file listed at path. If the file does not exist or cannot be opened for some other reason, `nil` is returned.
fileHandleForReadingFromURL:
url
error:
error
Description forthcoming.
fileHandleForUpdatingAtPath:
path
Returns an `NSFileHandle` object setup for updating (reading and writing) from the file listed at path. If the file does not exist or cannot be opened for some other reason, `nil` is returned.
fileHandleForUpdatingURL:
url
error:
error
Description forthcoming.
fileHandleForWritingAtPath:
path
Returns an `NSFileHandle` object set up for writing to the file listed at path. If the file does not exist or cannot be opened for some other reason, `nil` is returned.
fileHandleForWritingToURL:
url
error:
error
Description forthcoming.
fileHandleWithNullDevice
Returns a file handle object that is connected to the null device (i.e. a device that does nothing.) It is typically used in arrays and other collections of file handle objects as a place holder (null) object, so that all objects can respond to the same messages.
fileHandleWithStandardError
Returns an `NSFileHandle` object for the standard error descriptor. The returned object is a shared instance as there can only be one standard error per process.
fileHandleWithStandardInput
Returns an `NSFileHandle` object for the standard input descriptor. The returned object is a shared instance as there can only be one standard input per process.
fileHandleWithStandardOutput
Returns an `NSFileHandle` object for the standard output descriptor. The returned object is a shared instance as there can only be one standard output per process.
acceptConnectionInBackgroundAndNotify
Asynchronously accept a stream-type socket connection and act as the (server) end of the communications channel. This instance should have been created by -initWithFileDescriptor: with a stream-type socket created by the appropriate system routine. Posts a `NSFileHandleConnectionAcceptedNotification` when connection initiated, returning an `NSFileHandle` for the client side with that notification.
acceptConnectionInBackgroundAndNotifyForModes:
modes

Asynchronously accept a stream-type socket connection and act as the (server) end of the communications channel. This instance should have been created by -initWithFileDescriptor: with a stream-type socket created by the appropriate system routine. Posts a `NSFileHandleConnectionAcceptedNotification` when connection initiated, returning an `NSFileHandle` for the client side with that notification.

The modes array specifies NSRunLoop modes that the notification can be posted in.

availableData
Synchronously returns data available through this file or connection. If the handle represents a file, the entire contents from current file pointer to end are returned. If this is a network connection, reads what is available, blocking if nothing is available. Raises `NSFileHandleOperationException` if problem encountered.
closeFile
Disallows further reading from read-access files or connections, and sends EOF on write-access files or connections. Descriptor is only deleted when this instance is deallocated.
fileDescriptor
Return the underlying file descriptor for this instance.
getOffset:
offsetInFile
error:
error
Description forthcoming.
initWithFileDescriptor:
desc
Initialize with desc, which can point to either a regular file or socket connection.
initWithFileDescriptor:
desc
closeOnDealloc:
flag
Initialize with desc, which can point to either a regular file or socket connection. Close desc when this instance is deallocated if flag is `YES`.
initWithNativeHandle:
hdl
Windows-Unix compatibility support.
initWithNativeHandle:
hdl
closeOnDealloc:
flag
Windows-Unix compatibility support.
nativeHandle
Windows-Unix compatibility support.
offsetInFile
Return current position in file, or raises exception if instance does not represent a regular file.
readDataOfLength:
len
Reads up to len bytes from file or communications channel into return data.
readDataToEndOfFile
Reads up to maximum unsigned int bytes from file or communications channel into return data.
If the file is empty, returns an empty data item.
readInBackgroundAndNotify
Call -readInBackgroundAndNotifyForModes: with `nil` modes.
readInBackgroundAndNotifyForModes:
modes
Set up an asynchronous read operation which will cause a notification to be sent when any amount of data (or end of file) is read. Note that the file handle will not continuously send notifications when data is available. If you want to continue to receive notifications, you need to send this message again after receiving a notification.
readToEndOfFileInBackgroundAndNotify
Call -readToEndOfFileInBackgroundAndNotifyForModes: with `nil` modes.
readToEndOfFileInBackgroundAndNotifyForModes:
modes
Set up an asynchronous read operation which will cause a notification to be sent when end of file is read.
seekToEndOfFile
Position file pointer at end of file, raising exception if instance does not represent a regular file.
seekToEndReturningOffset:
offsetInFile
error:
error
Description forthcoming.
seekToFileOffset:
pos
Position file pointer at pos, raising exception if instance does not represent a regular file.
seekToOffset:
offset
error:
error
Description forthcoming.
synchronizeFile
Flush in-memory buffer to file or connection, then return.
truncateAtOffset:
offset
error:
error
Description forthcoming.
truncateFileAtOffset:
pos
Chops file beyond pos then sets file pointer to that point.
waitForDataInBackgroundAndNotify
Call -waitForDataInBackgroundAndNotifyForModes: with `nil` modes.
waitForDataInBackgroundAndNotifyForModes:
modes
Set up to provide a notification when data can be read from the handle.
writeData:
item
Synchronously writes given data item to file or connection.
Software documentation for the NSPipe class
Foundation/NSFileHandle.h

The NSPipe provides an encapsulation of the UNIX concept of pipe.
With NSPipe, it is possible to redirect the standard input or standard output.

The file handles created by NSPipe are automatically closed when they are no longer in use (ie when the NSPipe instance is deallocated), so you don't need to close them explicitly.

pipe
Returns a newly allocated and initialized NSPipe object that has been sent an autorelease message.
fileHandleForReading
Returns the file handle for reading from the pipe.
fileHandleForWriting
Returns the file handle for writing to the pipe.
Software documentation for the NSFileHandle(GNUstepExtensions) category
Foundation/NSFileHandle.h
A set of convenience methods for utilizing the socket communications capabilities of the NSFileHandle class.
fileHandleAsClientAtAddress:
address
service:
service
protocol:
protocol
Opens an outgoing network connection by initiating an asynchronous connection (see +fileHandleAsClientInBackgroundAtAddress:service:protocol:forModes:) and waiting for it to succeed, fail, or time out.
fileHandleAsClientInBackgroundAtAddress:
address
service:
service
protocol:
protocol
Opens an outgoing network connection asynchronously using [+fileHandleAsClientInBackgroundAtAddress:service:protocol:forModes:]
fileHandleAsClientInBackgroundAtAddress:
address
service:
service
protocol:
protocol
forModes:
modes

Opens an outgoing network connection asynchronously.

The address is the name (or IP dotted quad) of the machine to which the connection should be made.
The service is the name (or number) of the port to which the connection should be made.
The protocol is provided so support different network protocols, but at present only 'tcp' is supported. However, a protocol specification of the form 'socks-...' can be used to control socks5 support.
If '...' is empty (ie the string is just 'socks-' then the connection is not made via a socks server.
Otherwise, the text '...' must be the name of the host on which the socks5 server is running, with an optional port number separated from the host name by a colon.
Alternatively a prefix of the form 'bind-' followed by an IP address may be used (for non-socks connections) to ensure that the connection is made from the specified address.
If modes is `nil` or empty, uses NSDefaultRunLoopMode.

This method supports connection through a firewall via socks5. The socks5 connection may be controlled via the protocol argument, but if no socks information is supplied here, the GSSOCKS user default will be used, and failing that, the SOCKS5_SERVER or SOCKS_SERVER environment variables will be used to set the socks server. If none of these mechanisms specify a socks server, the connection will be made directly rather than through socks.

fileHandleAsServerAtAddress:
address
service:
service
protocol:
protocol
Opens a network server socket and listens for incoming connections using the specified service and protocol. The service is the name (or number) of the port to which the connection should be made. The protocol may at present only be 'tcp'
readDataInBackgroundAndNotifyLength:
len
Call -readDataInBackgroundAndNotifyLength:forModes: with `nil` modes.
readDataInBackgroundAndNotifyLength:
len
forModes:
modes
Set up an asynchronous read operation which will cause a notification to be sent when the specified amount of data (or end of file) is read.
readInProgress
Returns a boolean to indicate whether a read operation of any kind is in progress on the handle.
socketAddress
Returns the host address of the network connection represented by the file handle. If this handle is an incoming connection which was received by a local server handle, this is the name or address of the client machine.
socketLocalAddress
Returns the local address of the network connection or `nil`.
socketLocalService
Returns the local service/port of the network connection or `nil`.
socketProtocol
Returns the name of the protocol in use for the network connection represented by the file handle.
socketService
Returns the name (or number) of the service (network port) in use for the network connection represented by the file handle.
useCompression

Return a flag to indicate whether compression has been turned on for the file handle... this is only available on systems where GNUstep was built with 'zlib' support for compressing/decompressing data.

On systems which support it, this method may be called after a file handle has been initialised to turn on compression or decompression of the data being written/read.

Returns `YES` on success, `NO` on failure.
Reasons for failure are -
Not supported/built in to GNUstep
File handle has been closed
File handle is open for both read and write
Failure in compression/decompression library
writeInBackgroundAndNotify:
item
Call -writeInBackgroundAndNotify:forModes: with `nil` modes.
writeInBackgroundAndNotify:
item
forModes:
modes
Write the specified data asynchronously, and notify on completion.
writeInProgress
Returns a boolean to indicate whether a write operation of any kind is in progress on the handle. An outgoing network connection attempt (as a client) is considered to be a write operation.
Software documentation for the NSFileHandle(GNUstepTLS) category
Foundation/NSFileHandle.h
Where OpenSSL is available, you can use the subclass returned by +sslClass to handle SSL connections.
The -sslAccept method is used to do SSL handshake and start an encrypted session on a channel where the connection was initiated from the far end.
The -sslConnect method is used to do SSL handshake and start an encrypted session on a channel where the connection was initiated from the near end.
The -sslDisconnect method is used to end the encrypted session. The -sslSetCertificate:privateKey:PEMpasswd: method is used to establish a client certificate before starting an encrypted session.
NB. Some of these methods may block while performing I/O on the network connection, (though they should run the current runloop while doing so) so you should structure your code to handle that. In particular, if you are writing a server application, you should initiate a background accept to allow another incoming connection before you perform an -sslAccept on a connection you have just accepted.
setData:
data
forTLSFile:
fileName
Sets the known (cached) data content for the specified file name.
Calling this with a `nil` data object will remove any existing value from the cache.
You may use this method to control what data is used for specified file names when those file names are used as a result of SSL/TLS options being set for a file handle or stream.
sslClass
Returns the class to handle ssl enabled connections.
returns the concrete class used to implement SSL/TLS connections.
sslAccept
Repeatedly attempt an incoming handshake for up to 30 seconds or until the handshake completes.
sslConnect
Repeatedly attempt an outgoing handshake for up to 30 seconds or until the handshake completes.
sslDisconnect
Shuts down the SSL connection to the system that the handle is talking to.
sslHandshakeEstablished:
result
outgoing:
isOutgoing
Make a non-blocking handshake attempt. Calls to this method should be repeated until the method returns `YES` indicating that the handshake completed. If the method returns `YES` indicating completion of the handshake, the result indicates whether the handshake succeeded in establishing a connection or not.
The default implementation simply returns `YES` and sets result to `NO`.
This is implemented by an SSL handling subclass to perform real work.
sslIssuer
If the session verified a certificate from the remote end, returns the name of the certificate issuer in the form "C=xxxx,O=yyyy,CN=zzzz" as described in RFC2253. Otherwise returns `nil`.
sslOwner
If the session verified a certificate from the remote end, returns the name of the certificate owner in the form "C=xxxx,O=yyyy,CN=zzzz" as described in RFC2253. Otherwise returns `nil`.
sslSetCertificate:
certFile
privateKey:
privateKey
PEMpasswd:
PEMpasswd
Deprecated... use -sslSetOptions: instead
sslSetOptions:
options
Sets options to be used to configure this channel before the handshake.
Returns `nil` on success, or an error message if some options could not be set.
You may use the same options as property settings with the GNUstep implementation of NSStream.
Expects key value pairs with the following names/meanings:
GSTLSCAFile
A string identifying the full path to the file containing any trusted certificate authorities to be used when verifying a certificate presented by the remote end of a connection.
GSTLSCertificateFile
The path to a PEM encoded certificate used to identify this end of the connection. This option must be set for handing an incoming connection, but is optional for outgoing connections.
This must be used in conjunction with GSTLSCertificateKeyFile.
GSTLSCertificateKeyFile
The path to a PEM encoded key used to unlock the certificate file for the connection. The key in the file may or may not be encrypted, but if it is encrypted you must specify GSTLSCertificateKeyPassword.
GSTLSCertificateKeyPassword
A string to be used as the password to decrypt a key which was specified using GSTLSKeyPassword.
GSTLSDebug
A boolean specifying whether diagnostic debug is to be enabled to log information about a connection where the handshake fails.
GSTLSIssuers
An array of distinguished names (in RFC4514 format) listing the permitted issuers of the remote certificate. If this is present and the issuer of the remote certificate is not in the array, the connection handshake is failed.
GSTLSOwners
An array of distinguished names (in RFC4514 format) listing the permitted owners/subjects of the remote certificate. If this is present and the owner/subject of the remote certificate is not in the array, the connection handshake is failed.
GSTLSPriority
A GNUTLS priority string describing the ciphers etc which may be used for the connection. In addition the string may be one of SSLv3, or TLSv1 to use the appropriate general settings for negotiating a connection of the specified type.
GSTLSRemoteHosts
A comma delimited list of host names to be allowed when verifying the certificate of the host we are connecting to.
If this is not specified, all the names provided by NSHost are used.
GSTLSRevokeFile
The full path of a file containing certificate revocation information for certificates issued by our trusted authorites but no longer valid.
GSTLSServerName
By default the TLS layer when making an HTTPS request sets the 'Server Name Indication' (SNI) to be the name of the host in the URL that is being fetched.
This option allows the SNI to be set for other connections and permits overriding of the default behavior for HTTPS requests. Setting the value of GSTLSServerName to an empty string will prevent the SNI from being sent in the TLS handshake (this is sometimes desirable to prevent information leakage; the SNI information is sent unencrypted).
Some web servers require SNI in order to tell what hostname an HTTPS request is for and decide which certificate to present to the client.
GSTLSVerify
A boolean specifying whether we should require the remote end to supply a valid certificate in order to establish an encrypted connection.