Class: NSFileHandle

Inherits:
NSObject show all

Overview

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.

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods inherited from NSObject

#!, #!=, #!~, #, #==, #===, #=~, #Rational, #__callee__, #__method__, #__send__, #__type__, `, alloc, allocWithZone:, #autoContentAccessingProxy, autoload, autoload?, autorelease_pool, #awakeAfterUsingCoder:, binding, block_given?, caller, cancelPreviousPerformRequestsWithTarget:, cancelPreviousPerformRequestsWithTarget:selector:object:, catch, class, classFallbacksForKeyedArchiver, #classForCoder, #classForKeyedArchiver, classForKeyedUnarchiver, #clone, conformsToProtocol:, #copy, copyWithZone:, #dealloc, #define_singleton_method, description, display, #doesNotRecognizeSelector:, #dup, #enum_for, #eql?, #equal?, #extend, fail, #finalize, format, #forwardInvocation:, #forwardingTargetForSelector:, framework, #freeze, #frozen?, getpass, gets, global_variables, #init, initialize, #initialize_clone, #initialize_copy, #initialize_dup, #inspect, instanceMethodForSelector:, instanceMethodSignatureForSelector:, #instance_eval, #instance_exec, #instance_of?, #instance_variable_defined?, #instance_variable_get, #instance_variable_set, #instance_variables, instancesRespondToSelector:, isSubclassOfClass:, #is_a?, iterator?, #kind_of?, lambda, load, load_bridge_support_file, load_plist, local_variables, loop, #method, #methodForSelector:, #methodSignatureForSelector:, #methods, #mutableCopy, mutableCopyWithZone:, new, #nil?, open, p, #performSelector:onThread:withObject:waitUntilDone:, #performSelector:onThread:withObject:waitUntilDone:modes:, #performSelector:withObject:afterDelay:, #performSelector:withObject:afterDelay:inModes:, #performSelectorInBackground:withObject:, #performSelectorOnMainThread:withObject:waitUntilDone:, #performSelectorOnMainThread:withObject:waitUntilDone:modes:, print, printf, #private_methods, proc, #protected_methods, #public_method, #public_methods, #public_send, putc, puts, raise, rand, readline, readlines, #replacementObjectForCoder:, #replacementObjectForKeyedArchiver:, require, resolveClassMethod:, resolveInstanceMethod:, #respond_to?, #respond_to_missing?, select, #send, setVersion:, #singleton_methods, sprintf, srand, superclass, #taint, #tainted?, #tap, test, throw, #to_plist, #to_s, trace_var, trap, #trust, #untaint, untrace_var, #untrust, #untrusted?, version

Constructor Details

This class inherits a constructor from NSObject

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class NSObject

Class Method Details

+ (Object) fileHandleForReadingAtPath(path)

Returns a file handle initialized for reading the file, device, or named socket at the specified path. 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.

Parameters:

  • path (String)

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

Returns:

  • (Object)

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

+ (Object) fileHandleForReadingFromURL(url, error:error)

Returns a file handle initialized for reading the file, device, or named socket at the specified URL. 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.

Parameters:

  • url (NSURL)

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

  • error (Pointer)

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

Returns:

  • (Object)

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

+ (Object) fileHandleForUpdatingAtPath(path)

Returns a file handle initialized for reading and writing to the file, device, or named socket at the specified path. 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.

Parameters:

  • path (String)

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

Returns:

  • (Object)

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

+ (Object) fileHandleForUpdatingURL(url, error:error)

Returns a file handle initialized for reading and writing to the file, device, or named socket at the specified URL. 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.

Parameters:

  • url (NSURL)

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

  • error (Pointer)

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

Returns:

  • (Object)

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

+ (Object) fileHandleForWritingAtPath(path)

Returns a file handle initialized for writing to the file, device, or named socket at the specified path. 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.

Parameters:

  • path (String)

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

Returns:

  • (Object)

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

+ (Object) fileHandleForWritingToURL(url, error:error)

Returns a file handle initialized for writing to the file, device, or named socket at the specified URL. 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.

Parameters:

  • url (NSURL)

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

  • error (Pointer)

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

Returns:

  • (Object)

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

+ (Object) fileHandleWithNullDevice

Returns a file handle associated with a null device. 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.

Returns:

  • (Object)

    A file handle associated with a null device.

+ (Object) fileHandleWithStandardError

Returns the file handle associated with the standard error file. 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.

Returns:

  • (Object)

    The shared file handle associated with the standard error file.

+ (Object) fileHandleWithStandardInput

Returns the file handle associated with the standard input file. 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.

Returns:

  • (Object)

    The shared file handle associated with the standard input file.

+ (Object) fileHandleWithStandardOutput

Returns the file handle associated with the standard output file. 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.

Returns:

  • (Object)

    The shared file handle associated with the standard output file.

Instance Method Details

- (Object) acceptConnectionInBackgroundAndNotify

Accepts a socket connection (for stream-type sockets only) in the background and creates a file handle for the “near” (client) end of the communications channel. This method asynchronously creates a file handle for the other end of the socket connection and returns that object by posting a NSFileHandleConnectionAcceptedNotification notification in the current thread. The notification includes a userInfo dictionary with the created NSFileHandle object, which is accessible using the NSFileHandleNotificationFileHandleItem key.You must call this method from a thread that has an active run loop.

Returns:

- (Object) acceptConnectionInBackgroundAndNotifyForModes(modes)

Accepts a socket connection (for stream-type sockets only) in the background and creates a file handle for the “near” (client) end of the communications channel. See acceptConnectionInBackgroundAndNotify for details of how this method operates. This method differs from acceptConnectionInBackgroundAndNotify in that modes specifies the run-loop mode (or modes) in which NSFileHandleConnectionAcceptedNotification can be posted.You must call this method from a thread that has an active run loop.

Parameters:

  • modes (Array)

    The runloop modes in which the connection accepted notification can be posted.

Returns:

- (NSData) availableData

Returns the data currently available in the receiver. 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.

Returns:

  • (NSData)

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

- (Object) closeFile

Disallows further access to the represented file or communications channel and signals end of file on communications channels that permit writing. 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 NO 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.

Returns:

- (Integer) fileDescriptor

Returns the file descriptor associated with the receiver. 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.

Returns:

  • (Integer)

    The POSIX file descriptor associated with the receiver.

- (Object) initWithFileDescriptor(fileDescriptor)

Initializes and returns a file handle object associated with the specified file descriptor. 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.

Parameters:

  • fileDescriptor (Integer)

    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.

Returns:

  • (Object)

    A file handle initialized with fileDescriptor.

- (Object) initWithFileDescriptor(fileDescriptor, closeOnDealloc:flag)

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

Parameters:

  • fileDescriptor (Integer)

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

  • flag (Boolean)

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

Returns:

  • (Object)

    An initialized file handle object.

- (Integer) offsetInFile

Returns the position of the file pointer within the file represented by the receiver.

Returns:

  • (Integer)

    The position of the file pointer within the file represented by the receiver.

- (NSData) readDataOfLength(length)

Synchronously reads data up to the specified number of bytes. 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.

Parameters:

  • length (Integer)

    The number of bytes to read from the receiver.

Returns:

  • (NSData)

    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.

- (NSData) readDataToEndOfFile

Synchronously reads the available data up to the end of file or maximum number of bytes. This method invokes readDataOfLength: as part of its implementation.

Returns:

  • (NSData)

    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.

- (Object) readInBackgroundAndNotify

Reads from the file or communications channel in the background and posts a notification when finished. This method performs an asynchronous availableData operation on a file or communications channel and posts an NSFileHandleReadCompletionNotification notification on the current thread when that operation is complete. You must call this method from a thread that has an active run loop. The length of the data is limited to the buffer size of the underlying operating system. The notification includes a userInfo dictionary that contains the data read; access this object using the NSFileHandleNotificationDataItem key.Any object interested in receiving this data asynchronously must add itself as an observer of NSFileHandleReadCompletionNotification. In communication via stream-type sockets, the receiver is often the object returned in the userInfo dictionary of NSFileHandleConnectionAcceptedNotification.Note that this method does not cause a continuous stream of notifications to be sent. If you wish to keep getting notified, you’ll also need to call readInBackgroundAndNotify in your observer method.

Returns:

- (Object) readInBackgroundAndNotifyForModes(modes)

Reads from the file or communications channel in the background and posts a notification when finished. See readInBackgroundAndNotify for details of how this method operates. This method differs from readInBackgroundAndNotify in that modes specifies the run-loop mode (or modes) in which NSFileHandleReadCompletionNotification can be posted.You must call this method from a thread that has an active run loop.

Parameters:

  • modes (Array)

    The runloop modes in which the read completion notification can be posted.

Returns:

- (Object) readToEndOfFileInBackgroundAndNotify

Reads to the end of file from the file or communications channel in the background and posts a notification when finished. This method performs an asynchronous readToEndOfFile operation on a file or communications channel and posts an NSFileHandleReadToEndOfFileCompletionNotification. You must call this method from a thread that has an active run loop. The notification includes a userInfo dictionary that contains the data read; access this object using the NSFileHandleNotificationDataItem key.Any object interested in receiving this data asynchronously must add itself as an observer of NSFileHandleReadToEndOfFileCompletionNotification. In communication via stream-type sockets, the receiver is often the object returned in the userInfo dictionary of NSFileHandleConnectionAcceptedNotification.

Returns:

- (Object) readToEndOfFileInBackgroundAndNotifyForModes(modes)

Reads to the end of file from the file or communications channel in the background and posts a notification when finished. See readToEndOfFileInBackgroundAndNotify for details of this method's operation. The method differs from readToEndOfFileInBackgroundAndNotify in that modes specifies the run-loop mode (or modes) in which NSFileHandleReadToEndOfFileCompletionNotification can be posted.You must call this method from a thread that has an active run loop.

Parameters:

  • modes (Array)

    The runloop modes in which the read completion notification can be posted.

Returns:

- (Integer) seekToEndOfFile

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

Returns:

  • (Integer)

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

- (Object) seekToFileOffset(offset)

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

Parameters:

  • offset (Integer)

    The offset to seek to.

Returns:

- (Object) synchronizeFile

Causes all in-memory data and attributes of the file represented by the receiver to be written to permanent storage. 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.

Returns:

- (Object) truncateFileAtOffset(offset)

Truncates or extends the file represented by the receiver to a specified offset within the file and puts the file pointer at that position. If the file is extended (if offset is beyond the current end of file), the added characters are null bytes.

Parameters:

  • offset (Integer)

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

Returns:

- (Object) waitForDataInBackgroundAndNotify

Asynchronously checks to see if data is available. When the data becomes available, this method posts a NSFileHandleDataAvailableNotification notification on the current thread.You must call this method from a thread that has an active run loop.

Returns:

- (Object) waitForDataInBackgroundAndNotifyForModes(modes)

Asynchronously checks to see if data is available. When the data becomes available, this method posts a NSFileHandleDataAvailableNotification notification on the current thread. This method differs from waitForDataInBackgroundAndNotify in that modes specifies the run-loop mode (or modes) in which NSFileHandleDataAvailableNotification can be posted.You must call this method from a thread that has an active run loop.

Parameters:

  • modes (Array)

    The runloop modes in which the data available notification can be posted.

Returns:

- (Object) writeData(data)

Synchronously writes the specified data to the receiver. 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.

Parameters:

  • data (NSData)

    The data to be written.

Returns: