7.綜合樣本:尋找檔案
程式功能:尋找主目錄中某類型(.jpg)檔案並輸出找到的檔案清單。
NSFileManager提供對檔案系統的操作,如建立目錄、刪除檔案、移動檔案或者擷取檔案資訊。在這個例子裡,將使用NSFileManager建立NSdirectoryEnumerator來遍曆檔案的階層。
使用了兩種方法遍曆:俺索引枚舉 和 快速枚舉 (見注釋說明):
1 //
2 // Main.m
3 // FileWalker
4 // 尋找主目錄中某類型(.jpg)檔案並輸出找到的檔案清單。
5 //
6 // Created by Elf Sundae on 10/23/10.
7 // Copyright 2010 Elf.Sundae(at)Gmail.com. All rights reserved.
8 //
9 #import <Foundation/Foundation.h>
10
11 int main (int argc, const char * argv[]) {
12 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
13
14 // 建立NSFileManager
15 NSFileManager *fileManager = [NSFileManager defaultManager];
16 // 指定目錄為主目錄(~):(/Users/ElfSundae)
17 // stringByExpandingTildeInPath方法將路徑展開為fullpath
18 NSString *home = [@"~" stringByExpandingTildeInPath];
19 // 將路徑字串傳給檔案管理工具
20 //An NSDirectoryEnumerator object enumerates
21 //the contents of a directory, returning the
22 //pathnames of all files and directories contained
23 //within that directory. These pathnames are relative
24 //to the directory.
25 //You obtain a directory enumerator using
26 //NSFileManager’s enumeratorAtPath: method.
27
28 //* NSDirectoryEnumerator *direnum=[fileManager enumeratorAtPath:home];
29 //
30 // // 可以在迭代中直接輸出路徑。
31 // // 這裡先儲存到數組中再輸出
32 // NSMutableArray *files = [NSMutableArray arrayWithCapacity:42];
33 //
34 // NSString *fileName;
35 // while (fileName = [direnum nextObject]) {
36 // if ([[fileName pathExtension] isEqualTo:@"jpg"]) {
37 // [files addObject:fileName];
38 // }
39 //* }
40
41 // 或者使用快速枚舉迭代
42 NSMutableArray *files = [NSMutableArray arrayWithCapacity:42];
43 for (NSString *fileName in [fileManager enumeratorAtPath:home])
44 {
45 if ([[fileName pathExtension] isEqualTo:@"jpg"]) {
46 [files addObject:fileName];
47 }
48 }
49
50
51 //* NSEnumerator *jpgFiles = [files objectEnumerator];
52 // while (fileName = [jpgFiles nextObject]) {
53 // NSLog(@"%@",fileName);
54 //* }
55
56 // 或者用快速枚舉輸出
57 for ( NSString *jpg in files)
58 {
59 NSLog(@"%@",jpg);
60 }
61
62
63
64 [pool drain];
65 return 0;
66 }
67