Saturday, April 27, 2013

NSFileHandle fileHandleForWritingAtPath example ios


fileHandleForWritingAtPath:

Returns a file handle initialized for writing to the file, device, or named socket at the specified path.
+ (id)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 of [NSFileHandle fileHandleForWritingAtPath]
The file pointer is set to the beginning of the file. You cannot read data from the returned file handle object. Use thewriteData: 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.
Example of [NSFileHandle fileHandleForWritingAtPath]

NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
 self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName]; 
 NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
 if(output == nil) {
      [[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil];
      output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
 } else {
      [output seekToEndOfFile];
 }