public
Last active

NSArray+Globbing

  • Download Gist
NSArray+Globbing.h
Objective-C
1 2 3 4 5 6 7
#import <Foundation/Foundation.h>
 
@interface NSArray (Globbing)
 
+ (NSArray*) arrayWithFilesMatchingPattern: (NSString*) pattern inDirectory: (NSString*) directory;
 
@end
NSArray+Globbing.m
Objective-C
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
#import "NSArray+Globbing.h"
#include <glob.h>
 
@implementation NSArray (Globbing)
 
+ (NSArray*) arrayWithFilesMatchingPattern: (NSString*) pattern inDirectory: (NSString*) directory {
 
NSMutableArray* files = [NSMutableArray array];
glob_t gt;
NSString* globPathComponent = [NSString stringWithFormat: @"/%@", pattern];
NSString* expandedDirectory = [directory stringByExpandingTildeInPath];
char* fullPattern = [[expandedDirectory stringByAppendingPathComponent: globPathComponent] UTF8String];
if (glob(fullPattern, 0, NULL, &gt) == 0) {
int i;
for (i=0; i<gt.gl_matchc; i++) {
int len = strlen(gt.gl_pathv[i]);
NSString* filename = [[NSFileManager defaultManager] stringWithFileSystemRepresentation: gt.gl_pathv[i] length: len];
[files addObject: filename];
}
}
globfree(&gt);
return [NSArray arrayWithArray: files];
}
 
@end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.