需要获得目录的内容列表,使用enumeratorAtPath:方法或者directoryC ontentsAtPath:方法,可以完成枚举过程。
如果使用第一种enumeratorAtPath:方法,一次可以枚举指定目录中的每个文件。默认情况下,如果其中一个文件为目录,那么也会递归枚举它的内容。在这个过程中,通过向枚举对象发送一条skipDescendants消息,可以动态地阻止递归过程,从而不再枚举目录中的内容。
对于directoryContentsAtPath:方法,使用这个方法,可以枚举指定目录的内容,并在一个数组中返回文件列表。如果这个目录中的任何文件本身是个目录,这个方法并不递归枚举它的内容。
代码如下:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
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]) != nil)
{
NSLog(@"%@",path);
}
//遍历目录的另一种方法:(不递归枚举文件夹种的内容)
dirArray = [fm directoryContentsAtPath:[fm currentDirectoryPath]];
NSLog(@"2.Contents using directoryContentsAtPath:");
for(path in dirArray)
NSLog(@"%@",path);
}
return 0;
}
通过以上程序变例如下文件路径:
可以得到如下结果:
如果对上述代码while循环做如下修改,可以阻止任何子目录中的枚举:
while ((path = [dirEnum nextObject]) != nil)
{
NSLog(@"%@",path);
BOOL flag;
[fm fileExistsAtPath:path isDirectory:&flag];
if(flag == YES)
[dirEnum skipDescendants];
}
这里flag是一个BOOL类型的变量。如果指定的路径是目录,则fileExistsAtPath:在flag中存储YES,否则存储NO。
另外提醒下,无须像在这个程序中那样进行快速枚举,使用以下NSLog调用也可以显示所有的dirArray的内容:
NSLog(@"%@",dirArray);