Swift - writing a byte stream to file [closed]

ⅰ亾dé卋堺 提交于 2019-12-20 05:24:12

问题


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.


回答1:


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.




回答2:


Basically the issue is going to be getting your data correctly converted to a pointer to get it to NSOutputStream.write. The following extension should do what you need:

extension NSOutputStream {
    enum WriteErrors : ErrorType {
        case UTF8ConversionFailed
    }

    func write(string:String) throws -> Int {
        guard let data = string.dataUsingEncoding(NSUTF8StringEncoding) else {
            throw WriteErrors.UTF8ConversionFailed
        }

        return write(UnsafePointer(data.bytes), maxLength: data.length)
    }

    func write(var i:Int32) throws -> Int {
        return withUnsafePointer(&i) {
            self.write(UnsafePointer($0), maxLength: sizeof(Int32))
        }
    }
}

Note that writing raw binary data to a file is ill-advised, you should be standardizing the byte order first, but I leave that as an exercise for the reader.



来源:https://stackoverflow.com/questions/36120854/swift-writing-a-byte-stream-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!