user3009804
user3009804

Reputation: 349

File count of a directory in Objective-C

I would like to know how can I get the total amount of archives inside of a directory, for example desktop. I don't just want to know what's inside of the root of the directory, but also inside of its subfolders.

To just get the archives on the root of desktop I can do the following:

NSArray *directoryContent  = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
NSUInteger numberOfFileInFolder = [directoryContent  count];

But I need to get also the count of its subfolders.

Can somebody help me?

Edit: Finally I have coded this way:

-(int) numberOfDocumentsInPath: (NSString *) path{
    NSFileManager *manager = [[NSFileManager alloc] init];

    NSDirectoryEnumerator* totalSubpaths = [manager enumeratorAtPath: path];

    NSLog(@"Path %@ has %d documents", path, (int)[[totalSubpaths allObjects] count]);

    return (int)[[totalSubpaths allObjects] count];
}

Upvotes: 1

Views: 1491

Answers (3)

Esqarrouth
Esqarrouth

Reputation: 39201

Swift version:

var subs = NSFileManager.defaultManager().subpathsOfDirectoryAtPath(path, error: nil) as! [String]
var filecount = subs.count
println(filecount)

for sub in subs {
    //Do stuff with files
}

Upvotes: 2

bhavya kothari
bhavya kothari

Reputation: 7474

Try this:

 NSDirectoryEnumerator *subs = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:FolderPath error:nil];

Upvotes: 3

cacau
cacau

Reputation: 3646

Straight from the docs:

If you need to recurse into subdirectories, use enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: as shown in “Using a Directory Enumerator”).

Check also here: Using a Directory Enumerator

Upvotes: 2

Related Questions