案例1:通过文件扩展名进行搜索文件

  1.       NSFileManager *manager = [NSFileManager defaultManager];
  2.         /*
  3.          在Mac OS X系统有一个代表主目录的速记符号~(也成为代字符)。
  4.          stringByExpandingTildeInPath将~替换成当前用户的主目录。
  5.          enumeratorAtPath:返回一个NSDictionaryEnumerator,它是NSEnumerator的子类。每次在这个枚举器对象中调用nextObject时,都会返回该目录中一个文件的另一个路径。这个方法也能搜索子目录。
  6.          */
  7.         NSString *home = [@"~" stringByExpandingTildeInPath];
  8.         //
  9.         NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:home];
  10.         NSMutableArray *files = [NSMutableArray arrayWithCapacity:32];
  11.         NSString *filename;
  12.         NSLog(@"请输入要查询的文件类型:");
  13.         char extension[10];
  14.         scanf("%s",extension);
  15.    //将C语言字符串转OC字符串
  16.         NSString *exten = [NSString stringWithFormat:@"%s",extension];
  17.         while (filename = [direnum nextObject]) {
  18.             if ([[filename pathExtension]isEqualTo:exten]) {
  19.                 [files addObject:filename];
  20.                 
  21.             }
  22.         }
  23.         NSEnumerator *fileenum;
  24.         fileenum = [files objectEnumerator];
  25.         while (filename =[fileenum nextObject]) {
  26.             NSLog(@"%@",filename);
  27.         }

 

案例2:通过文件名进行搜索文件

 

  1. #import <Foundation/Foundation.h>
  2. int main(int argc, const char * argv[]) {
  3.     @autoreleasepool {
  4.         NSFileManager *manager = [NSFileManager defaultManager];
  5.         /*
  6.          在Mac OS X系统有一个代表主目录的速记符号~(也成为代字符)。
  7.          stringByExpandingTildeInPath将~替换成当前用户的主目录。
  8.          enumeratorAtPath:返回一个NSDictionaryEnumerator,它是NSEnumerator的子类。每次在这个枚举器对象中调用nextObject时,都会返回该目录中一个文件的另一个路径。这个方法也能搜索子目录。
  9.          */
  10.         NSString *home = [@"~" stringByExpandingTildeInPath];
  11.         //获取主目录下的文件路径
  12.         NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:home];
  13.         //声明一个足够大的数组来保存搜索到的文件路径
  14.         NSMutableArray *files = [NSMutableArray arrayWithCapacity:100];
  15.         NSString *path;
  16.         NSLog(@"请输入要查询的文件名:");
  17.         char fileName[10];
  18.         scanf("%s",fileName);
  19.         //字符串转NSString
  20.         NSString *exten = [NSString stringWithUTF8String:fileName];
  21.         while (path = [direnum nextObject]) {
  22.             //对路径进行分割
  23.             NSArray *array = [path pathComponents];
  24.             NSString *obj;
  25.             for(obj in array)
  26.             {
  27.                 //对路径的分割部分进行检索,比对,如果等于要输入的文件名,进行另外保存
  28.                 if ([obj isEqualTo:exten]) {
  29.                     [files addObject:path];
  30.                     break;
  31.                 }
  32.             }
  33.         
  34.         }
  35.         //遍历搜索结果
  36.         for(id obj in files)
  37.         {
  38.             NSLog(@"%@",obj);
  39.         }
  40.     }
  41.     return 0;
  42. }