IPhone binary data recording

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

+5
source share
2 answers

Experimented 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 strange thing is that the written file seems to be 8 bytes, not 4. It is even possible to initialize nsdata with a length of 0, add a float and then write, and then the file will be 4 bytes. Why does NSData add 4 bytes by default? An NSData with a length of 4 should contain a file of length 4, not 8.

+6
source

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

I usually create an NSFileHandle and then write binary data as follows:

NSFileHandle handle*;
float f;

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

All Articles