需要获得目录的内容列表,使用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;
-
}
使用NSFileManager枚举目录种的内容(遍历目录)
原文:http://blog.csdn.net/yangchen9931/article/details/44975795