0

For writing and reading gigabytes of data I want control at the byte level. Unfortunately I find it extremely difficult to make sense of raw byte access with the available documentation and resources.

What I'd like to get running is a Swift 3 equivalent of the following C code

#include <stdlib.h>
#include <stdio.h>

int main() {
    int N=300;
    size_t bufsz = N*sizeof(uint8_t) + N*sizeof(double);
    uint8_t *buffer = malloc(bufsz);

    size_t ofs=0;
    while (ofs<bufsz) {
        *(buffer+ofs) = 'A';
        ofs += sizeof(uint8_t);
        *((double*)(buffer+ofs)) = 6.0138242189890428e-154;
        ofs += sizeof(double);
    }

    FILE *file = fopen("foo.bin", "w");
    fwrite(buffer, bufsz, sizeof(uint8_t), file);
    fclose(file);
}

How does this translate to Swift?

Frederick Squid
  • 591
  • 4
  • 16
  • You should check this answer: http://stackoverflow.com/questions/24097826/read-and-write-data-from-text-file – jvarela Nov 29 '16 at 22:51
  • The focus of this question is not so much on writing to a file but rather on getting complete control over a buffer. I guess the writing to file part will be done with `Data.write(to: URL)` but how to get this data set up is what I'm trying to find out. – Frederick Squid Nov 29 '16 at 22:58
  • @FrederickSquid Have you looked into `Data.init(bytes: [UInt8])`? – Tim Vermeulen Nov 29 '16 at 23:13

0 Answers0