使用NSFileManager枚举目录种的内容(遍历目录)

来源:互联网 发布:典型数据报表图片 编辑:程序博客网 时间:2024/06/07 03:45

需要获得目录的内容列表,使用enumeratorAtPath:方法或者directoryC ontentsAtPath:方法,可以完成枚举过程。

如果使用第一种enumeratorAtPath:方法,一次可以枚举指定目录中的每个文件。默认情况下,如果其中一个文件为目录,那么也会递归枚举它的内容。在这个过程中,通过向枚举对象发送一条skipDescendants消息,可以动态地阻止递归过程,从而不再枚举目录中的内容。

对于directoryContentsAtPath:方法,使用这个方法,可以枚举指定目录的内容,并在一个数组中返回文件列表。如果这个目录中的任何文件本身是个目录,这个方法并不递归枚举它的内容。

代码如下:

[cpp] view plain copy
  1. #import <Foundation/Foundation.h>  
  2.   
  3. int main(int argc, const char * argv[])  
  4. {  
  5.   
  6.     @autoreleasepool {  
  7.           
  8.         NSString *path;  
  9.         NSFileManager *fm;  
  10.         NSDirectoryEnumerator *dirEnum;  
  11.         NSArray *dirArray;  
  12.           
  13.         fm = [NSFileManager defaultManager];  
  14.           
  15.         //获取当前的工作目录的路径  
  16.         path = [fm currentDirectoryPath];  
  17.           
  18.         //遍历这个目录的第一种方法:(深度遍历,会递归枚举它的内容)  
  19.         dirEnum = [fm enumeratorAtPath:path];  
  20.           
  21.         NSLog(@"1.Contents of %@:",path);  
  22.         while ((path = [dirEnum nextObject]) != nil)  
  23.         {  
  24.             NSLog(@"%@",path);  
  25.         }  
  26.           
  27.         //遍历目录的另一种方法:(不递归枚举文件夹种的内容)  
  28.         dirArray = [fm directoryContentsAtPath:[fm currentDirectoryPath]];  
  29.         NSLog(@"2.Contents using directoryContentsAtPath:");  
  30.           
  31.         for(path in dirArray)  
  32.             NSLog(@"%@",path);     
  33.           
  34.     }  
  35.     return 0;  
  36. }  

通过以上程序变例如下文件路径:


可以得到如下结果:


如果对上述代码while循环做如下修改,可以阻止任何子目录中的枚举:

[cpp] view plain copy
  1. while ((path = [dirEnum nextObject]) != nil)  
  2. {  
  3.       
  4.     NSLog(@"%@",path);  
  5.       
  6.     BOOL flag;  
  7.     [fm fileExistsAtPath:path isDirectory:&flag];  
  8.     if(flag == YES)  
  9.         [dirEnum skipDescendants];  
  10. }  


这里flag是一个BOOL类型的变量。如果指定的路径是目录,则fileExistsAtPath:在flag中存储YES,否则存储NO。

另外提醒下,无须像在这个程序中那样进行快速枚举,使用以下NSLog调用也可以显示所有的dirArray的内容:

[cpp] view plain copy
  1. NSLog(@"%@",dirArray);  
0 0
原创粉丝点击