views:

336

answers:

4

I am trying to count entire files in a directory, including subdirectories. This is what I have to count files in the first folder:

-(NSString *)numberOfPhotos
{
    NSString *MyPath = @"/rootdirectory/"; 
    NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath:MyPath]; 

    return [NSString stringWithFormat:@"%d", [directoryContent count]];
}

I was thinking maybe something like

for (file in folder){
    [file count]
{

but doesnt seem to work.

UPDATE: Actually, was very easy:

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

Are you sure this path exists @"/rootdirectory/". Have you tried @"/"?

Shaji
yes, the path i used here is an example, but the path does exist and counts each object in the "rootdirectory" just not in any sub directories IN the "rootdirectory".
AWright4911
+2  A: 

You're on the right track. You need a recursive method. You pass in a directory, the method grabs all of the files in the directory, then checks each one to see if it is a directory or not. Here you'd have a for loop to check if the current object is a directory. If it is a directory, then it would call itself with the directory name. If not, it increments a counter by one and continues.

Can't post code right now, but that's the way you'd do it.

Jordan
plz post when you can!
AWright4911
I posted some pseudo code so you can see the recursive algorithm in another answer.
progrmr
+1, nitpick corner: You don't exactyly _need_ a recursive algorithm to traverse a tree, but certainly it's easier ;-)
Johannes Rudolph
A: 

See if I can write code using the iPad keyboard... Using pseudo code to describe the recursive algorithm:

int fileCount(directory)
{
    int count = 0;
    for (file in directory)
    {
        if (isDirectory(file))
            count += fileCount(file);
        else
            count++;
    }
    return count;
}                
progrmr
A: 
NSDirectoryEnumerator *subs = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:musicPath error:nil];
AWright4911