Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift append to file if exists or create file otherwise [duplicate]

Tags:

file

swift

I want to write a String to a file. If the file doesn't exist it should be created. If it does, the String should be appended.

I tried:

    let data = text.data(using: String.Encoding.utf8)
    let filemgr = FileManager.default
    let path = filemgr.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last?.appendingPathComponent("out.txt")
    if !filemgr.fileExists(atPath: (path?.absoluteString)!) {
        filemgr.createFile(atPath: (path?.absoluteString)!, contents: data, attributes: nil)
    } else {
        var file = FileHandle(forReadingAtPath: (path?.absoluteString)!)
        let databuffer = String(describing: file?.readDataToEndOfFile())
        file = FileHandle(forWritingAtPath: (path?.absoluteString)!)
        if file != nil {

            file?.seek(toFileOffset: 10)
            file?.write(data!)
            file?.closeFile()
        }
    }

so far the file doesn't even seem to get created, since it jumps to the createFile every time. what am I doing wrong?

like image 968
Ginso89 Avatar asked Apr 19 '18 07:04

Ginso89


1 Answers

Use (path?.path)! instead of (path?.absoluteString)!.

like image 168
Chanchal Chauhan Avatar answered Nov 07 '22 09:11

Chanchal Chauhan