Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C get list of files and subfolders in a directory

Tags:

objective-c

What is the trick to get an array list of full file/folder paths from a given directory? I'm looking to search a given directory for files ending in .mp3 and need the full path name that includes the filename.

NSArray* dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error:Nil];

NSArray* mp3Files = [dirs filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.mp3'"]];

this only returns the file name not the path

like image 738
Tsukasa Avatar asked Nov 12 '13 09:11

Tsukasa


People also ask

How can I get a list of all the subfolders and files present in a directory using PHP?

PHP using scandir() to find folders in a directory The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.


2 Answers

It's probably best to enumerate the array using a block, which can be used to concatenate the path and the filename, testing for whatever file extension you want:

NSArray* dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath
                                                                    error:NULL];
NSMutableArray *mp3Files = [[NSMutableArray alloc] init];
[dirs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSString *filename = (NSString *)obj;
    NSString *extension = [[filename pathExtension] lowercaseString];
    if ([extension isEqualToString:@"mp3"]) {
        [mp3Files addObject:[sourcePath stringByAppendingPathComponent:filename]];
    }
}];
like image 85
trojanfoe Avatar answered Oct 09 '22 08:10

trojanfoe


To use a predicate on URLs I would do it this way:

NSURL *bundleRoot = [[NSBundle mainBundle] bundleURL];
NSArray * dirContents = 
      [fm contentsOfDirectoryAtURL:bundleRoot
        includingPropertiesForKeys:@[] 
                           options:NSDirectoryEnumerationSkipsHiddenFiles
                             error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension='.mp3'"];
NSArray *mp3Files = [directoryContents filteredArrayUsingPredicate:predicate];

This question may be a duplicate: Getting a list of files in a directory with a glob

There is also the NSDirectoryEnumerator object which is great for iterating through files in a directory.

like image 36
Infinity James Avatar answered Oct 09 '22 08:10

Infinity James