fileHandleForWritingToURL :error:
Returns a file handle initialized for writing to the file, device, or named socket at the specified URL.
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. PassNULL
if you do not want error information.
Return Value of [NSFileHandle fileHandleForWritingToURL]
The initialized file handle object or
nil
if no file exists at url.Discussion of [NSFileHandle fileHandleForWritingToURL]
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.
Example of [NSFileHandle fileHandleForWritingToURL]
static const NSUInteger BufferSize = 1024*1024;
@implementation ALAsset (Export)
- (BOOL) exportDataToURL: (NSURL*) fileURL error: (NSError**) error
{
[[NSFileManager defaultManager] createFileAtPath:[fileURL path] contents:nil attributes:nil];
NSFileHandle *handle = [NSFileHandle fileHandleForWritingToURL:fileURL error:error];
if (!handle) {
return NO;
}
ALAssetRepresentation *rep = [self defaultRepresentation];
uint8_t *buffer = calloc(BufferSize, sizeof(*buffer));
NSUInteger offset = 0, bytesRead = 0;
do {
@try {
bytesRead = [rep getBytes:buffer fromOffset:offset length:BufferSize error:error];
[handle writeData:[NSData dataWithBytesNoCopy:buffer length:bytesRead freeWhenDone:NO]];
offset += bytesRead;
} @catch (NSException *exception) {
free(buffer);
return NO;
}
} while (bytesRead > 0);
free(buffer);
return YES;
}