Search code examples
swiftfilebytestream

Swift - writing a byte stream to file


I have a string of several hundred bytes and some Int32 values. I want to write these to a file, verbatim.

I have tried many suggested solutions and none have worked for me. I get extraneous brackets or spaces or commas in the file.

Can anyone suggest a simple, reliable solution?

I thought my question was very clear, but after reading the comments, I have simplified it.

How do I write and/or append "12345" to a file so that the file contains the following Hex values: 3132333435 ?

The best result I can obtain is <3132333435>, by writing an NSData string.

I can get the desired result using this link: Does swift have a protocol for writing a stream of bytes?, but I cannot append data to the file I have created.


Solution

  • I would suggest using NSFileHandle.

    I tested like this. I started with a file ~/Desktop/test.txt containing the word "testing". I then ran this code:

        let s = "12345"
        let d = s.dataUsingEncoding(NSASCIIStringEncoding)!
        let path = ("~/Desktop/test.txt" as NSString).stringByExpandingTildeInPath
        if let fh = NSFileHandle(forWritingAtPath: path) {
            fh.seekToEndOfFile()
            fh.writeData(d)
            fh.closeFile()
        }
    

    The result was that the file now contained

    testing12345
    

    A hex dump revealed that the underlying bytes were:

    74 65 73 74 69 6E 67 31 32 33 34 35
    

    I believe that's what you said you wanted to achieve.

    Also, one further commment:

    The best result I can obtain is <3132333435>

    It sounds here as if the problem is merely that you don't know how to read the console output. The < and > are not really in the file; they are just part of the console representation of data. It would be better to use BBEdit / TextWrangler or a dedicated hex dumper to see the actual byte of the file.