views:

679

answers:

2

How do you delete all the contents of a directory without deleting the directory itself? I want to basically empty a folder yet leave it (and the permissions) intact.

+2  A: 

Try this:

NSFileManager *manager = [ NSFileManager defaultManager ];

NSString *dirToEmpty = ... //directory to empty

NSError *error;

NSArray *files = [ manager contentsOfDirectoryAtPath: dirToEmpty error: &error ];

for( NSString *file in files ) {
    if( file != @"." && file != @".." ) {
        [ manager removeItemAtPath: [ dirToEmpty stringByAppendingPathComponent: file ] error: &error ];
        if( error ) { 
           //an error occurred...
        }
    }    
}
Jacob Relkin
`contentsOfDirectoryAtPath::` doesn't give you the full path of the contents.
Georg Fritzsche
Works too... :)
Nano8Blazex
+4  A: 

E.g. by using a directory enumerator:

NSFileManager* fm = [[[NSFileManager alloc] init] autorelease];
NSDirectoryEnumerator* en = [fm enumeratorAtPath:path];    
NSError* err = nil;
BOOL res;

while (NSString* file = [en nextObject]) {
    res = [fm removeItemAtPath:[path stringByAppendingPathComponent:file] error:&err];
    if (!res && err) {
        NSLog(@"oops: %@", err);
    }
}
Georg Fritzsche
Works perfectly.
Nano8Blazex
Don't forget to check whether `removeItemAtPath:` actually failed before attempting to use the error object. At the very least, you may report more errors than you actually have.
Peter Hosey
@Peter: Oops, thanks.
Georg Fritzsche