iPhone writing binary data

拟墨画扇 提交于 2019-12-17 19:24:26

问题


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?


回答1:


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.




回答2:


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));


来源:https://stackoverflow.com/questions/1526416/iphone-writing-binary-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!