Delete text file content

I read and write 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) 
+6
source share
3 answers

Just write an empty line to the file as follows:

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

If you configured NSFileHandle , you can use -truncateFileAtOffset: passing 0 for the offset.

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

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

+2
source

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) } 
+1
source

All Articles