0

// Write a Double to file, works OK

func writeData() {

var oStream: NSOutputStream?
let folder = NSSearchPathForDirectoriesInDomains(.DesktopDirectory, .UserDomainMask, true)[0] as! String
let path = folder.stringByAppendingPathComponent(fileName)
oStream = NSOutputStream(toFileAtPath: path, append: false)
oStream!.open()

var val = 9.81
let foo = NSData(bytes: &val, length: sizeof(Double))
oStream!.write(UnsafePointer(foo.bytes), maxLength: sizeof(Double))
oStream!.close()

}

// Read a Double from file

func readData() {

var iStream: NSInputStream?
let folder = NSSearchPathForDirectoriesInDomains(.DesktopDirectory, .UserDomainMask, true)[0] as! String
let path = folder.stringByAppendingPathComponent(fileName)
iStream = NSInputStream(fileAtPath: path)
iStream!.open()

var buffer = [UInt8](count: sizeof(Double), repeatedValue: 0)
iStream!.read(&buffer, maxLength: sizeof(Double))

// Question: how to get the Double value back out of buffer?

iStream!.close()

}

Gary M
  • 11
  • 2
  • The referenced question is about writing an Int32, but the answer works for all "simple" types like Double as well. – Martin R May 18 '15 at 16:30
  • Oh, never mind, I realized that I can use "memcpy" to convert from array of bytes back to Double. I have so many ignorant questions. – Gary M May 19 '15 at 07:18
  • You don't need memcpy or an intermediate array, you can read into a Double directly, compare http://stackoverflow.com/questions/25845574/convert-an-objective-c-method-into-swift-for-nsinputstream-convert-bytes-into-d. – I do hope that the referenced threads answer your questions. Otherwise let me know and I'll reopen the question. – Martin R May 19 '15 at 07:24
  • I appreciate your help a lot. I can now do everything I need to do in terms of file streaming, just need to ensure I can use fseek() or similar function, but I will do that later. – Gary M May 19 '15 at 18:38

0 Answers0