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

2019-08-30 07:23发布

问题:

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.