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
2010-05-05 01:35:32
`contentsOfDirectoryAtPath::` doesn't give you the full path of the contents.
Georg Fritzsche
2010-05-05 01:43:56
Works too... :)
Nano8Blazex
2010-05-05 05:12:19
+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
2010-05-05 01:39:51
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
2010-05-08 03:35:32