quano
quano

Reputation: 19122

iPhone writing binary data

How do you write binary data to a file? I want to write floats to a file, raw, and then read them back as floats. How do you do that?

Upvotes: 6

Views: 8722

Answers (2)

Sulthan
Sulthan

Reputation: 130122

Note that Objective-C is only an extension of C programming language.

I usually create a NSFileHandle and then write binary data this way:

NSFileHandle handle*;
float f;

write([handle fileDescriptor], &f, sizeof(float));

Upvotes: 3

quano
quano

Reputation: 19122

Been experimenting with this:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *file = [documentsDirectory stringByAppendingPathComponent:@"binaryData"];

float b = 32.0f;

NSMutableData *data = [NSMutableData dataWithLength:sizeof(float)];
[data appendBytes:&b length:sizeof(float)];
[data writeToFile:file atomically:YES];

NSData *read = [NSData dataWithContentsOfFile:file];
float b2;
NSRange test = {0,4};
[read getBytes:&b2 range:test];

The weird thing is that the file written seems to be 8 bytes and not 4. It is even possible to init the nsdata with 0 length, append a float and then write, and then the file will be 4 bytes. Why is NSData adding 4 bytes by default? A NSData with length 4 should result in a file with length 4, not 8.

Upvotes: 6

Related Questions