I’m having trouble figuring out how to write binary data files to my hard drive and read them back in.
I’m using OS X Command Line Tool application in Xcode 6 and swift (I understand it’s a Foundation thing and not a swift thing).
I’m looking for help / info / resource for understanding how to create, open, write to, and read Doubles from a file in my documents directory. Eventually i’ll need to write and read an array of Doubles.
I’ve received advice to use NSStream and NSData, but haven’t been able to put it all together.
I have a C#.net background and there it was pretty straightforward.
I’ve been all over the web and there doesn’t seem to be a clear explanation. Basic texts don’t even touch the subject. I can’t imagine it can be that hard. Any help would be appreciated. Thanks!
Writing files to disk and reading them back in is pretty easy to do, especially if you can code in C or C++.
This can also be done in Objective-C by using an NSData object.
First, read the NSData class reference to familiarise yourself with the following methods:
+ (instancetype)dataWithBytes:(const void *)bytes length:(NSUInteger)length
- (BOOL)writeToFile:(NSString *)path options:(NSDataWritingOptions)mask error:(NSError **)errorPtr
+ (instancetype)dataWithContentsOfFile:(NSString *)path
Here is a complete code example:
// main.m
// Data
//
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
@autoreleasepool {
// Write the numbers from 0 to 20 to a file and read them back in
//
NSString * dataFile = @"~/tmp/0-20.data";
dataFile = [dataFile stringByStandardizingPath];
const double v [] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
const unsigned long vN = sizeof (v) / sizeof (v [0]);
const unsigned long vNumBytes = sizeof (v);
// store them in a data object
NSData * outData = [NSData dataWithBytes:v length:vNumBytes];
assert (outData);
// write to file
NSError * error = nil;
[outData writeToFile:dataFile options:NSDataWritingAtomic error:&error];
NSLog (@"error: %@", error);
assert (error == nil);
// read then back in
NSData * inData = [NSData dataWithContentsOfFile];
assert (inData);
assert (inData.length == vNumBytes);
// now verify...
double iv [vN];
[inData getBytes:iv length:vNumBytes];
for (unsigned long x = 0; x < vN; ++x) {
assert (v [x] == iv [x]);
}
}
return 0;
}
[Become a competent programmer: pretty-function.org]
Thanks for the code sample. I was hoping to write this all in swift, but I’ll study your example and try to adapt it.
Thanks again!!! - John