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?
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 .
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.
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With