139

For some crazy reason I can't find a way to get a list of files with a glob for a given directory.

I'm currently stuck with something along the lines of:

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSArray *dirContents = [[NSFileManager defaultManager] 
                        directoryContentsAtPath:bundleRoot];

..and then stripping out the stuff I don't want, which sucks. But what I'd really like is to be able to search for something like "foo*.jpg" instead of asking for the entire directory, but I've not been able to find anything like that.

So how the heck do you do it?

TheNeil
  • 3,321
  • 2
  • 27
  • 52
sammich
  • 335
  • 5
  • 13
  • 19
  • Brian Webster's answer helped me out a lot in a similar issue. http://stackoverflow.com/questions/5105250/run-nsbundle-from-the-documents-folder/7179584#7179584 – Wytchkraft Aug 24 '11 at 20:15
  • 1
    Just side note to anyone reading this, you may be able to solve this by just putting your files into a folder http://stackoverflow.com/questions/1762836/create-a-folder-inside-documents-folder-in-ios-apps – seo Aug 25 '14 at 02:14

10 Answers10

242

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];
ssc
  • 9,528
  • 10
  • 64
  • 94
Brian Webster
  • 11,915
  • 4
  • 44
  • 58
  • this looks great! is there a way to format the predicate to catch two file types at once, such as '.jpg' and '.png'? – mtmurdock Mar 15 '11 at 15:09
  • 5
    Yeah, you can add additional logic using OR statements, e.g. "self ENDSWITH '.jpg' OR self ENDSWITH '.png'" – Brian Webster Mar 15 '11 at 18:31
  • 3
    You can use the "pathExtension == '.xxx'" instead of "ENDSWITH". Look this [answer](http://stackoverflow.com/questions/5032541/nspredicate-endswith-multiple-files) – Bruno Berisso Apr 26 '12 at 12:35
  • "pathExtension='.jpg'" should be "pathExtension='jpg'". If you include the '.' this doesn't work, pathExtension looks for everything after the '.' – Andrew Feb 24 '14 at 21:35
  • using `@"self ENDSWITH '.jpg'"` with an NSURL fails with `Can't do a substring operation with something that isn't a string` as the array contains URLs, not strings, but I can't seem to figure out how to elegantly transform every array item; probably also beyond the scope of the question... – ssc Jan 12 '15 at 18:32
33

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);            
    }       
}
Matt
  • 1,167
  • 1
  • 15
  • 26
28

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.

John Biesnecker
  • 3,782
  • 2
  • 34
  • 43
  • You should use `contentsOfDirectoryAtPath:error:` instead of `directoryContentsAtPath` because its `deprecated` since `iOS` 2.0 – Alex Cio Feb 27 '14 at 12:28
12

Very Simplest Method:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager contentsOfDirectoryAtPath:documentsDirectory 
                                                 error:nil];
//--- Listing file by name sort
NSLog(@"\n File list %@",fileList);

//---- Sorting files by extension    
NSArray *filePathsArray = 
  [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  
                                                      error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF EndsWith '.png'"];
filePathsArray =  [filePathsArray filteredArrayUsingPredicate:predicate];
NSLog(@"\n\n Sorted files by extension %@",filePathsArray);
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
Rajesh Loganathan
  • 11,129
  • 4
  • 78
  • 90
10

Unix has a library that can perform file globbing operations for you. The functions and types are declared in a header called glob.h, so you'll need to #include it. If open up a terminal an open the man page for glob by typing man 3 glob you'll get all of the information you need to know to use the functions.

Below is an example of how you could populate an array the files that match a globbing pattern. When using the glob function there are a few things you need to keep in mind.

  1. By default, the glob function looks for files in the current working directory. In order to search another directory you'll need to prepend the directory name to the globbing pattern as I've done in my example to get all of the files in /bin.
  2. You are responsible for cleaning up the memory allocated by glob by calling globfree when you're done with the structure.

In my example I use the default options and no error callback. The man page covers all of the options in case there's something in there you want to use. If you're going to use the above code, I'd suggest adding it as a category to NSArray or something like that.

NSMutableArray* files = [NSMutableArray array];
glob_t gt;
char* pattern = "/bin/*";
if (glob(pattern, 0, NULL, &gt) == 0) {
    int i;
    for (i=0; i<gt.gl_matchc; i++) {
        [files addObject: [NSString stringWithCString: gt.gl_pathv[i]]];
    }
}
globfree(&gt);
return [NSArray arrayWithArray: files];

Edit: I've created a gist on github that contains the above code in a category called NSArray+Globbing.

Bryan Kyle
  • 13,361
  • 4
  • 40
  • 45
  • `stringWithCString:` is deprecated. The correct replacement is `-[NSFileManager stringWithFileSystemRepresentation:length:]`, although I think most people use `stringWithUTF8String:` (which is easier but not guaranteed to be the right encoding). – Peter Hosey Feb 03 '10 at 19:58
5

You need to roll your own method to eliminate the files you don't want.

This isn't easy with the built in tools, but you could use RegExKit Lite to assist with finding the elements in the returned array you are interested in. According to the release notes this should work in both Cocoa and Cocoa-Touch applications.

Here's the demo code I wrote up in about 10 minutes. I changed the < and > to " because they weren't showing up inside the pre block, but it still works with the quotes. Maybe somebody who knows more about formatting code here on StackOverflow will correct this (Chris?).

This is a "Foundation Tool" Command Line Utility template project. If I get my git daemon up and running on my home server I'll edit this post to add the URL for the project.

#import "Foundation/Foundation.h"
#import "RegexKit/RegexKit.h"

@interface MTFileMatcher : NSObject 
{
}
- (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath;
@end

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    MTFileMatcher* matcher = [[[MTFileMatcher alloc] init] autorelease];
    [matcher getFilesMatchingRegEx:@"^.+\\.[Jj][Pp][Ee]?[Gg]$" forPath:[@"~/Pictures" stringByExpandingTildeInPath]];

    [pool drain];
    return 0;
}

@implementation MTFileMatcher
- (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath;
{
    NSArray* filesAtPath = [[[NSFileManager defaultManager] directoryContentsAtPath:inPath] arrayByMatchingObjectsWithRegex:inRegex];
    NSEnumerator* itr = [filesAtPath objectEnumerator];
    NSString* obj;
    while (obj = [itr nextObject])
    {
        NSLog(obj);
    }
}
@end
Mark
  • 6,108
  • 3
  • 34
  • 49
3

I won't pretend to be an expert on the topic, but you should have access to both the glob and wordexp function from objective-c, no?

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
2

stringWithFileSystemRepresentation doesn't appear to be available in iOS.

Oscar
  • 2,039
  • 2
  • 29
  • 39
0

Swift 5

This works for cocoa

        let bundleRoot = Bundle.main.bundlePath
        let manager = FileManager.default
        let dirEnum = manager.enumerator(atPath: bundleRoot)


        while let filename = dirEnum?.nextObject() as? String {
            if filename.hasSuffix(".data"){
                print("Files in resource folder: \(filename)")
            }
        }
black_pearl
  • 2,549
  • 1
  • 23
  • 36
0

Swift 5 for cocoa

        // Getting the Contents of a Directory in a Single Batch Operation

        let bundleRoot = Bundle.main.bundlePath
        let url = URL(string: bundleRoot)
        let properties: [URLResourceKey] = [ URLResourceKey.localizedNameKey, URLResourceKey.creationDateKey, URLResourceKey.localizedTypeDescriptionKey]
        if let src = url{
            do {
                let paths = try FileManager.default.contentsOfDirectory(at: src, includingPropertiesForKeys: properties, options: [])

                for p in paths {
                     if p.hasSuffix(".data"){
                           print("File Path is: \(p)")
                     }
                }

            } catch  {  }
        }
dengST30
  • 3,643
  • 24
  • 25