Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone writing binary data

Tags:

iphone

binary

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?

like image 643
quano Avatar asked Oct 06 '09 15:10

quano


People also ask

How do you write data in a binary file?

To write to a binary fileUse the WriteAllBytes method, supplying the file path and name and the bytes to be written. This example appends the data array CustomerData to the file named CollectedData. dat .

What is IOS binary?

ios::binary makes sure the data is read or written without translating new line characters to and from \r\n on the fly. In other words, exactly what you give the stream is exactly what's written.

How do I read or write binary data?

To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable. When opened using any text editor, the data is unrecognizable.

Which method is used for writing data in binary?

The BinaryWriter Class. The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor.


2 Answers

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.

like image 97
quano Avatar answered Sep 27 '22 23:09

quano


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));
like image 34
Sulthan Avatar answered Sep 28 '22 01:09

Sulthan