0

I am adding .txt file to Documents folder for storing some data using solution founded here: Read Text File in Document Folder - Iphone SDK

So now I can write and read text from this file succesfully, but I need also to have action what will clear all text in this file to make it absolutely empty. Is it possible?

Community
  • 1
  • 1
Olex
  • 1,656
  • 3
  • 20
  • 38
  • 1
    well, the simplest way would be to delete the file then create a new one with the same name. you can use [this tutorial](http://mobiledevelopertips.com/data-file-management/iphone-file-system-creating-renaming-and-deleting-files.html) to learn how to do that. – Oren Feb 03 '13 at 16:30

2 Answers2

5

In one line, this ought to do it:

[[NSData data] writeToFile: pathToFile atomically: YES];
ipmcc
  • 29,581
  • 5
  • 84
  • 147
2

This will loop all files -in Documents Directory- which has suffix of "txt" and delete its contents:

NSString* path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSArray *arr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
for (NSString *fileName in arr) {
    if ([fileName hasSuffix:@".txt"])
    {
        [@"" writeToFile:[path stringByAppendingPathComponent:fileName] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
}
Aziz
  • 612
  • 1
  • 6
  • 11
  • As of iOS 8, do **not** use this to get the Documents folder. It is no longer just off of the "home" directory. – rmaddy Aug 13 '15 at 00:36