Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective c: How to only delete all file under a directory but keep the directory itself

I found the code below to delete file in objective-c, but I want to only delete all files under directory of Caches and keep the directory Caches itself.

Could someone suggest the method to do that?

Thanks

NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr removeItemAtPath: [NSHomeDirectory() stringByAppendingString:@"/Library/Caches"] error: NULL]  == YES)
        NSLog (@"Remove successful");
else
        NSLog (@"Remove failed");

UPDATED

NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr removeItemAtPath: [NSHomeDirectory() stringByAppendingString:@"/Library/Caches"] error: NULL]  == YES)
    NSLog (@"Remove successful");
else
    NSLog (@"Remove failed");

[filemgr createDirectoryAtPath: [NSHomeDirectory() stringByAppendingString:@"/Library/Caches"] withIntermediateDirectories:NO attributes:nil error:nil];
like image 340
Charles Yeung Avatar asked Mar 02 '12 08:03

Charles Yeung


1 Answers

Loop through the files in that directory.

NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *fileArray = [fileMgr contentsOfDirectoryAtPath:directory error:nil];
for (NSString *filename in fileArray)  {

    [fileMgr removeItemAtPath:[directory stringByAppendingPathComponent:filename] error:NULL];
}
like image 109
Hanon Avatar answered Nov 03 '22 14:11

Hanon