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
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.
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]];
}
}];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With