TurtleFan
TurtleFan

Reputation: 289

Deleting contents of text file

I'm reading and writing to a text file. There is an instance where I want to delete the contents of the file (but not the file) as a kind of reset. How can I do this?

if ((dirs) != nil) {
    var dir = dirs![0]; //documents directory

    let path = dir.stringByAppendingPathComponent("UserInfo.txt");
    println(path)
    let text = "Rondom Text"

    //writing
    text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)

    //reading
    let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)

    println(text2)

Upvotes: 11

Views: 7726

Answers (3)

Alessandro Ornano
Alessandro Ornano

Reputation: 35402

Swift 3.x

let text = ""
do {
     try text.write(toFile: fileBundlePath, atomically: false, encoding: .utf8)
} catch {
     print(error)
}

Swift 4.x

let text = ""
do {
     try text.write(to: filePath, atomically: false, encoding: .utf8)
   } catch {
     print(error)
   }

Upvotes: 4

Bannings
Bannings

Reputation: 10479

Simply write an empty string to the file like this:

let text = ""
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)

Upvotes: 11

jtbandes
jtbandes

Reputation: 118731

If you set up an NSFileHandle, you can use -truncateFileAtOffset:, passing 0 for the offset.

Or, as pointed out in comments, you can simply write an empty string or data to the file.

Or you can use some kind of data structure / database that does not require you to manually truncate files :)

Upvotes: 9

Related Questions