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

qco9c6ql  于 2023-02-10  发布在  iOS
关注(0)|答案(3)|浏览(126)

我找到了下面的代码来删除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];
ny6fqffe

ny6fqffe1#

遍历该目录中的文件。

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

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

xtfmy6hx2#

试试这个

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/"]];
//Load from File
NSFileManager *fileManage=  [NSFileManager defaultManager];
[fileManage   removeItemAtPath:myPathDocs error:NULL];
bxfogqkk

bxfogqkk3#

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

相关问题