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)
jtbandes
  • 115,675
  • 35
  • 233
  • 266
TurtleFan
  • 289
  • 2
  • 17

3 Answers3

11

Simply write an empty string to the file like this:

let text = ""
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
Bannings
  • 10,376
  • 7
  • 44
  • 54
7

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

jtbandes
  • 115,675
  • 35
  • 233
  • 266
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)
   }
IOS Singh
  • 617
  • 6
  • 15
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133