Deleting contents of text file
Asked Answered
W

3

11

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)
Woofer answered 23/8, 2015 at 5:16 Comment(4)
Did you get any error with your code?Smarten
Nothing wrong with the above code. I would just like to know how to delete the contents of the file... i.e. here I'm writing to the file and then the user presses reset, so the file becomes empty.Woofer
"".writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil) The file will have cleared.Smarten
If that solved your issue, please accept my answer :)Smarten
S
11

Simply write an empty string to the file like this:

let text = ""
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
Smarten answered 23/8, 2015 at 6:3 Comment(0)
P
9

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 :)

Pressroom answered 23/8, 2015 at 5:49 Comment(0)
K
4

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)
   }
Koh answered 7/7, 2017 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.