List Files In A Directory And All Subdirectores

April 2, 2013

Following is a few lines of Objective-C code to quickly traverse a directory and all of its subdirectories.

Let’s start with a file structure in the Documents directory that I used for my example:

The example I am writing is using the simulator, thus the folder structure shown above is from my Mac. However, the same applies regardless of the platform.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
NSFileManager *fileMgr;
NSString *entry;
NSString *documentsDir;
NSDirectoryEnumerator *enumerator;
BOOL isDirectory;
 
// Create file manager
fileMgr = [NSFileManager defaultManager];
 
// Path to documents directory
documentsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
 
// Change to Documents directory
[fileMgr changeCurrentDirectoryPath:documentsDir];
 
// Enumerator for docs directory
enumerator = [fileMgr enumeratorAtPath:documentsDir];
 
// Get each entry (file or folder)
while ((entry = [enumerator nextObject]) != nil)
{
  // File or directory
  if ([fileMgr fileExistsAtPath:entry isDirectory:&isDirectory] && isDirectory)
    NSLog (@"Directory - %@", entry);
  else
    NSLog (@"  File - %@", entry);
}

Line 17 is the most relevant line of code, wherein the enumerator manages traversing the current directory and all subdirectories. From there I check whether or not the object returned is a file or directory and output the results.

Leave a Comment