目标c:如何只删除目录下的所有文件,但保留目录本身

时间:2012-03-02 08:30:09

标签: iphone objective-c ios

我找到了以下代码来删除objective-c中的文件,但我只想删除Caches目录下的所有文件,并保留目录Caches本身。

有人可以建议这样做的方法吗?

由于

NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

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

已更新

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];

2 个答案:

答案 0 :(得分:40)

循环浏览该目录中的文件。

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

    [fileMgr removeItemAtPath:[directory stringByAppendingPathComponent:filename] error:NULL];
}

答案 1 :(得分:0)

- (void) removeDocuments
{
    NSString *docDir = // get documents directory
    NSString *cacheDir = [docDir stringByAppendingPathComponent: @"cacheDir"];

    // check if cache dir exists

    // get all files in this directory
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *fileList = [fm contentsOfDirectoryAtPath: cacheDir error: nil];

    // remove
    for(NSInteger i = 0; i < [fileList count]; ++i)
    {
        NSString *fp =  [fileList objectAtIndex: i];
        NSString *remPath = [cacheDir stringByAppendingPathComponent: fp];
        [fm removeItemAtPath: remPath error: nil];
    }
}