Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 693
TurtleFan Avatar asked Aug 23 '15 05:08

TurtleFan


People also ask

How do you delete contents of a text file?

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.


2 Answers

Simply write an empty string to the file like this:

let text = ""
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
like image 163
Bannings Avatar answered Sep 19 '22 09:09

Bannings


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

like image 45
jtbandes Avatar answered Sep 18 '22 09:09

jtbandes