Reputation: 141
I am looking for a simple way in Objective-C to select all of the .jpg files in a directory. Right now I can only get all of the directory contents. Is there a way to apply a wildcard, like *.jpg, to the results?
if ( [[NSFileManager defaultManager] isReadableFileAtPath:@"/folder2/"] )
[[NSFileManager defaultManager] copyItemAtPath:@"/folder2/" toPath:@"/folder1/" error:nil];
Upvotes: 1
Views: 660
Reputation: 124997
Pretty much straight from the docs:
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir];
NSString *file;
while (file = [dirEnum nextObject]) {
if ([[file pathExtension] isEqualToString: @"jpg"]) {
// process the document
[self doSomethingWithFile: [docsDir stringByAppendingPathComponent:file]];
}
}
It looks like NSDirectoryEnumerator also supports fast enumeration, so you could use that instead:
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir];
for (NSString *file in dirEnum) {
if ([[file pathExtension] isEqualToString: @"doc"]) {
// process the document
[self doSomethingWithFile: [docsDir stringByAppendingPathComponent:file]];
}
}
The difference between using a directory enumerator and iterating over the list returned by -contentsOfDirectoryAtPath:
is that the directory enumerator will also provide results from subdirectories.
Upvotes: 1
Reputation: 5779
You could use something like:
NSArray *list = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/folder2/" error:nil];
for (NSString* file in list) {
if ([[file pathExtension] isEqualToString: @"jpg"]) {
[[NSFileManager defaultManager] copyItemAtPath:file toPath:@"/folder1/" error:nil];
}
}
The contentsOfDirectoryAtPath:error
method returns an array containing the names of the files in the specified directory. For each entry, the result of the NSString
pathExtension
method is compared against the target string ("jpg"). Any matching files are copied into the destination directory.
Upvotes: 3