Count files in directories AND subdirectories? iPhone
-
26-09-2019 - |
Question
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];
Solution
NSDirectoryEnumerator *subs = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:musicPath error:nil];
OTHER TIPS
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.
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;
}