My solution was along the following lines but it seems mighty ugly.
Anyone know of a better way?
// Open and create the file using POSIX open in <fcntl.h>
int segment_fd = open([segment_file_path UTF8String], O_WRONLY |
O_CREAT | O_APPEND | O_TRUNC, 0666);
NSAssert1(segment_fd >= 0, @"Error opening file descriptor for @%",
segment_file_path);
// Wrap the file descriptor up in an NSFileHandle
segment_file_handle = [[NSFileHandle alloc]
initWithFileDescriptor:segment_fd closeOnDealloc:YES];
// Insert multiple calls to [segment_file_handle writeData:data];
[segment_file_handle closeFile]; // Unnecessary?
[segment_file_handle release]; // Closes fd
Regards,
Wes
> Working on a Mac app where I want to open a file that doesn't already
> exist and write chunks of NSData to it incrementally. NSFileHandle has
> a method fileHandleForWritingAtPath: but that requires the file to
> already exist. Most of the other file writing routines I found are
> designed to write data once and that's it, not keep the handle open to
> receive more data.
>
> My solution was along the following lines but it seems mighty ugly.
> Anyone know of a better way?
You could use NSFileManager's createFileAtPath:contents:attributes: to
create the file, then open it.
Pete Yandell
http://notahat.com/
It seems strange I can't find a standard pattern for this. I'd imagine
that most apps that download from a network link would want to write
as they go to a new file. I'll have to do some more researching.
Wes
Adium had a couple of spots where it did what I did and I found one
place in the Omni Frameworks where they did what Pete suggested ie.
[[NSFileManager defaultManager] createFileAtPath:aFilename
contents:[NSData data] attributes:requestedFileAttributes];
newFileHandle = [NSFileHandle fileHandleForWritingAtPath:aFilename];
So it seems either are accepted solutions and there is no "standard" way.
WM
michael
2008/9/29 Wesley Moore <wjm...@gmail.com>: