我已经制作了这个小代码来检查给定目录中有多少个子目录。它只检查第一级,无论如何我可以使它更简单吗?我添加了评论,也许更容易理解我的意图。谢谢!
#import < Foundation/Foundation.h > int main (int argc, const char * argv[]){
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
NSFileManager *filemgr;
NSMutableArray *listOfFiles;
NSDictionary *listOfFolders;
NSDictionary *controllDir;
int i, count;
NSString *myPath;
filemgr = [NSFileManager defaultManager];
myPath = @"/";
// list the files in the given directory (myPath)
listOfFiles = [filemgr directoryContentsAtPath: myPath];
// count the number of elements in the array
count = [listOfFiles count];
// check them one by one
for (i = 0; i < count; i++)
{
// I need the full path
NSString *filePath =[NSString stringWithFormat:@"%@/%@", myPath, [listOfFiles objectAtIndex: i]];
// add every item with its attributes
listOfFolders = [filemgr attributesOfItemAtPath:filePath error:NULL];
// to avoid typo get the attribute and create a string
controllDir = [filemgr attributesOfItemAtPath:@"/" error:NULL];
NSString *toCheck = [NSString stringWithFormat:@"%@", [controllDir objectForKey:NSFileType]];
// the folder elements one by one
NSString *fileType = [NSString stringWithFormat:@"%@", [listOfFolders objectForKey:NSFileType]];
if([toCheck isEqualToString:fileType])
{
NSLog(@"NAME: %@ TYPE: %@" ,[listOfFiles objectAtIndex:i],[listOfFolders objectForKey:NSFileType]);
}
}
[pool drain];
return 0;
}
答案 0 :(得分:1)
NSURL *url = [NSURL fileURLWithPath:@"/Users"];
NSError *error;
NSArray *items = [[NSFileManager defaultManager]
contentsOfDirectoryAtURL:url
includingPropertiesForKeys:[NSArray array]
options:0
error:&error];
NSMutableArray *dirs = [NSMutableArray array];
for (NSURL *url in items) {
if (CFURLHasDirectoryPath((CFURLRef)url)) {
[dirs addObject:url];
}
}
}
你可以通过这种方式获得幻想:
NSPredicate *predicate = [NSPredicate predicateWithBlock:
^BOOL (id evaluatedObject, NSDictionary *bindings){
return CFURLHasDirectoryPath((CFURLRef)evaluatedObject); }];
NSArray *dirs = [items filteredArrayUsingPredicate:predicate]);
值得注意的是,它只会一次击中磁盘,并且不会花费任何时间来获取不需要的属性。一旦构造了NSURL
,就可以随时判断它是否是一个目录,因为它以/结尾(这是指定的行为)。这就是CFURLHasDirectoryPath()
正在做的事情。它实际上并没有击中磁盘。
答案 1 :(得分:1)
简短的想法(从手机发布):
NSDirectoryEnumerator
。fileAttributes
的方法,它会返回带有项目属性的NSDictionary
。 NSDictionary
有一个fileType
方法,它会返回一个常量来指示项目的类型。 NSFileTypeDirectory
,可用于比较。 答案 2 :(得分:0)
这是怎么回事?
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error;
NSArray *subpaths = [fm contentsOfDirectoryAtPath:myPath error:&error];
if (!subpaths) ...handle error.
NSMutableArray *subdirs = [NSMutableArray array];
for (NSString *name in subpaths)
{
NSString *subpath = [myPath stringByAppendingPathComponent:name];
BOOL isDir;
if ([fm fileExistsAtPath:subpath isDirectory:&isDir] &&
isDir)
{
[subdirs addObject:subpath];
}
}
现在subdirs
数组包含所有直接子目录。