迅速.如何将文本行附加到 file.txt 的顶部? [英] Swift. How to append text line to top of file.txt?

查看:29
本文介绍了迅速.如何将文本行附加到 file.txt 的顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个小型记录器,在其中写入 TXT 文件.我希望最后一个事件位于文件的顶部,但我无法使其正常工作.网上的例子都是用fileHandle.seekToEndOfFile()"写在文件末尾.

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.

这就是我所拥有的:

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?

谢谢!!

推荐答案

这应该没问题:首先,获取旧数据,然后追加新数据并写入所有内容.

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.

这篇关于迅速.如何将文本行附加到 file.txt 的顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆