需要获得目录的内容列表,使用enumeratorAtPath:方法或者directoryContentsAtPath:方法,可以完成枚举过程,其中directoryContentsAtPath:方法在10.5被舍弃,现在用contentsOfDirectoryAtPath:error:方法。
如果使用第一种enumeratorAtPath:方法,一次可以枚举指定目录中的每个文件。默认情况下,如果其中一个文件为目录,那么也会递归枚举它的内容。在这个过程中,通过向枚举对象发送一条skipDescendants消息,可以动态地阻止递归过程,从而不再枚举目录中的内容。
对于contentsOfDirectoryAtPath:error:方法,使用这个方法,可以枚举指定目录的内容,并在一个数组中返回文件列表。如果这个目录中的任何文件本身是个目录,这个方法并不递归枚举它的内容。
附上代码:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
NSString *path;
NSFileManager *fm;
NSDirectoryEnumerator *dirEnum;
NSArray *dirArray;
fm = [NSFileManager defaultManager];
//获取当前的工作目录的路径
path = [fm currentDirectoryPath];
//遍历这会目录的第一种方法:(深度遍历,会递归枚举它的内容)
dirEnum = [fm enumeratorAtPath:path];
NSLog(@"1.contents of %@:",path);
while (path = [dirEnum nextObject]) {
NSLog(@"%@",path);
}
//遍历目录的另一种方法:(不递归枚举文件夹中的内容)
dirArray = [fm contentsOfDirectoryAtPath:[fm currentDirectoryPath] error:nil];
NSLog(@"2.contents using contentsOfDirectoryAtPath:error:");
for (path in dirArray) {
NSLog(@"%@",path);
}
}
return 0;
}
通过以上程序遍历如下文件路径:可以得到以下结果:
另外,如果对上述代码中while循环做如下修改,可以阻止任何子目录中的枚举:
while (path = [dirEnum nextObject]) {
NSLog(@"%@",path);
BOOL flag = [fm fileExistsAtPath:path isDirectory:nil];
if (flag) {
[dirEnum skipDescendants];
}
}
这个效果和使用contentsOfDirectoryAtPath:error:的效果是一样的。。