Sean
Sean

Reputation: 333

Get the count of files in a directory

How can I count the files in a directory? I couldn't find anything relevant in the class reference of NSFileManager.

Upvotes: 8

Views: 4341

Answers (3)

yhlin
yhlin

Reputation: 189

subpathsOfDirectoryAtPath:error: returns an array with all path of target directory include sub-directory.

But as the document says,"you might not want to use it in performance-critical code."

Upvotes: 0

Ali Saeed
Ali Saeed

Reputation: 1569

contentsOfDirectoryAtPath:error: returns an NSArray of everything in a directory (Files + Folders).

To get a count of files only, you can filter as follows:

NSMutableArray *files = [[NSMutableArray alloc] init];
NSArray *itemsInFolder = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderpath error:NULL];

NSString *itemPath;
BOOL isDirectory;
for (NSString *item in itemsInFolder){
    itemPath = [NSString stringWithFormat:@"%@/%@", folderpath, item];
    [[NSFileManager defaultManager] fileExistsAtPath:item isDirectory:&isDirectory];
    if (!isDirectory) {
        [files addObject:item];
    }
}

return [files count];

Upvotes: 3

Benedict Cohen
Benedict Cohen

Reputation: 11920

contentsOfDirectoryAtPath:error: returns an NSArray. Just send count to the array.

Upvotes: 14

Related Questions