Getting a list of files in a directory with a glob Getting a list of files in a directory with a glob ios ios

Getting a list of files in a directory with a glob


You can achieve this pretty easily with the help of NSPredicate, like so:

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];NSFileManager *fm = [NSFileManager defaultManager];NSArray *dirContents = [fm contentsOfDirectoryAtPath:bundleRoot error:nil];NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"];NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];

If you need to do it with NSURL instead it looks like this:

NSURL *bundleRoot = [[NSBundle mainBundle] bundleURL];NSArray * dirContents =       [fm contentsOfDirectoryAtURL:bundleRoot        includingPropertiesForKeys:@[]                            options:NSDirectoryEnumerationSkipsHiddenFiles                             error:nil];NSPredicate * fltr = [NSPredicate predicateWithFormat:@"pathExtension='jpg'"];NSArray * onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];


This works quite nicely for IOS, but should also work for cocoa.

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];NSFileManager *manager = [NSFileManager defaultManager];NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];NSString *filename;while ((filename = [direnum nextObject] )) {    //change the suffix to what you are looking for    if ([filename hasSuffix:@".data"]) {           // Do work here        NSLog(@"Files in resource folder: %@", filename);                }       }


What about using NSString's hasSuffix and hasPrefix methods? Something like (if you're searching for "foo*.jpg"):

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];NSArray *dirContents = [[NSFileManager defaultManager] directoryContentsAtPath:bundleRoot];for (NSString *tString in dirContents) {    if ([tString hasPrefix:@"foo"] && [tString hasSuffix:@".jpg"]) {        // do stuff    }}

For simple, straightforward matches like that it would be simpler than using a regex library.