Re: to write to file except NSData*
Re: to write to file except NSData*
- Subject: Re: to write to file except NSData*
- From: Jeff LaMarche <email@hidden>
- Date: Tue, 15 Apr 2008 11:14:42 -0400
On Apr 15, 2008, at 10:38 AM, Nick Rogers wrote:
Hi,
I am creating a file with:
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:path contents:nil attributes:nil];
===========
then I got a fileHandle as:
NSFileHandle *fileHandle = [NSFileHandle
fileHandleForWritingAtPath:path];
===========
NSFileHandle has the method:
- (void)writeData:(NSData *)data
=====================
but i want to write the length of (NSData *)data, before I write it
to file because I will be writing a lot of NSData to the file,
so that I will be able to read the length first and then read the
following NSData.
SO how can I write the length which is an integer to file before I
write the NSData.
How is your length stored? Is it a short, or an int or an NSUInteger?
One way I think you could tackle this would be to create an NSData
that contains the length, write that first, then use:
[fileHandle truncateFileAtOffset:[aFileHandle seekToEndOfFile]];
which sets the file handle to write at the end of the file - basically
to append data, then use writeData: as you said.
But there's a caveat here - we currently have both big-endian and
little-endian Macs running OS X and NSData doesn't deal with
endianness automatically - that's our responsibility. There are ways
to convert, such as the byte ordering functions documented here:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html
or you could also store the length as a string:
NSString *lengthString = [NSString stringWithFormat:@"%d", theLength];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:path contents:nil attributes:nil];
NSFileHandle *fileHandle = [NSFileHandle
fileHandleForWritingAtPath:path[;
[fileHandle writeData:[lengthString
dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle truncateFileAtOffset:[fileHandle seekToEndOfFile]];
[fileHandle writeData:myActualNSDataObject];
etc.
HTH. This is untested code typed in e-mail, so I suspect there are
errors, but hopefully it will point you in the right direction.
Jeff
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden