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?
Asked
Active
Viewed 8,690 times
2 Answers
6
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.

quano
- 18,812
- 25
- 97
- 108
-
Can you use a hex editor to examine the contents of the file when it has 8 bytes? Seems to me you should be able to pick out which 4 are your float and the other 4 may give you a clue as to what's going wrong. – Tim Oct 06 '09 at 16:46
-
Indeed. The last 4 is the float. The file looks like this: 00 00 00 00 00 00 00 42 – quano Oct 06 '09 at 16:53
-
Apparently initing a NSMutableData with a length causes it to append that length to its data and point to the space afterwards. Initing it with length 0 is the solution. Then one can ask oneself why one would want to init it with any other length than 0 at all. – quano Oct 06 '09 at 19:49
3
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));

Sulthan
- 128,090
- 22
- 218
- 270