目标c:如何只删除目录下的所有文件,但保留目录本身 [英] Objective c: How to only delete all file under a directory but keep the directory itself

查看:81
本文介绍了目标c:如何只删除目录下的所有文件,但保留目录本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现下面的代码删除了objective-c中的文件,但我只想删除 Caches 目录下的所有文件并保留目录缓存本身。

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?

谢谢

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


推荐答案

循环遍历该目录中的文件。

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

这篇关于目标c:如何只删除目录下的所有文件,但保留目录本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆