7. comprehensive example: Searching for files
Program function: Find a local file (.jpg) in the main directory and output the list of found files.
Nsfilemanager provides operations on the file system, such as creating directories, deleting files, moving files, or obtaining file information. In this example, nsfilemanager is used to create nsdirectoryenumerator to traverse the File hierarchy.
Two methods are used for traversal: Index enumeration and quick enumeration (see notes ):
1 //
2 // main. m
3 // filewalker
4 // search for a local file (.jpg) in the main directory and output the list of found files.
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 NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init];
13
14 // create nsfilemanager
15 nsfilemanager * filemanager = [nsfilemanager defamanager manager];
16 // specify the directory as the main directory (~) :(/Users/elfsundae)
17 // The stringbyexpandingtildeinpath method expands the path to fullpath.
18 nsstring * home = [@"~ "Stringbyexpandingtildeinpath];
19 // pass the path string to the File Manager
20 // an nsdirectoryenumerator object enumerates
21 // The contents of a directory, returning
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 //// you can directly output the path in the iteration.
31 //// store it in the array before outputting it
32 // nsmutablearray * files = [nsmutablearray arraywithcapacity: 42];
33 //
34 // nsstring * filename;
35 // while (filename = [direnum nextobject]) {
36 // If ([[filename pathextension] isdue to: @ "jpg"]) {
37 // [files addobject: Filename];
38 //}
39 //*}
40
41 // or use Quick enumeration Iteration
42 nsmutablearray * files = [nsmutablearray arraywithcapacity: 42];
43 for (nsstring * filename in [filemanager enumeratoratpath: Home])
44 {
45 if ([[filename pathextension] isdue to: @ "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 // or use Quick enumeration output
57 for (nsstring * JPG in files)
58 {
59 nslog (@ "% @", JPG );
60}
61
62
63
64 [pool drain];
65 return 0;
66}
67