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)
Clear a Text File Using the open() Function in write Mode Opening a file in write mode will automatically delete the file's contents. The open() function takes two arguments, the text file we'd like to open and the mode we're opening it in. Opening a file in write mode clears its data.
Simply write an empty string to the file like this:
let text = ""
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With