Swift. How to append text line to top of file.txt?

天大地大妈咪最大 提交于 2019-12-24 19:15:45

问题


I am implementing a small logger, in which I am writing to a TXT file. I wanted the last event to be at the top of the file but I'm having trouble getting this to work. All examples on the internet are using "fileHandle.seekToEndOfFile()" to write at the end of the file.

This is what I have:

private static func writeToFile(text: String) {

        guard let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return }
        guard let writePath = NSURL(fileURLWithPath: path).appendingPathComponent(Logger.folderName) else { return }
        let fileManager = FileManager.default

        try? fileManager.createDirectory(atPath: writePath.path, withIntermediateDirectories: true)
        let file = writePath.appendingPathComponent(Logger.fileName)

        if !fileManager.fileExists(atPath: file.path) {
            do {
                try "".write(toFile: file.path, atomically: true, encoding: String.Encoding.utf8)
            } catch _ {
            }
        }

        let msgWithLine = text + "\n"
        do {
            let fileHandle = try FileHandle(forWritingTo: file)
            //fileHandle.seekToEndOfFile()
            fileHandle.write(msgWithLine.data(using: .utf8)!)
            fileHandle.closeFile()
        } catch {
            print("Error writing to file \(error)")
        }
    }

With this code, I write in the first line but nevertheless, I am always rewriting what is on the first line.

How can I change this to whatever is in the first be taken to a line below and then write new content in the first line?

Thank you!!


回答1:


This should be okay: First, get the old data and after that append the new one and write everything.

let msgWithLine = text + "\n"
do {
    let fileHandle = try FileHandle(forWritingTo: file)
    fileHandle.seek(toFileOffset: 0)
    let oldData = try String(contentsOf: file, encoding: .utf8).data(using: .utf8)!
    var data = msgWithLine.data(using: .utf8)!
    data.append(oldData)
    fileHandle.write(data)
    fileHandle.closeFile()
} catch {
    print("Error writing to file \(error)")
}

I didn't test the code it may have some problems.

Another possible solution is to write at the end of the file and to invert the file when you read it.



来源:https://stackoverflow.com/questions/56441768/swift-how-to-append-text-line-to-top-of-file-txt

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