Reputation: 5745
I'm trying to read directories, and then get the path for the files in those directories. The problem is, I don't know how many subdirectories there may be in a folder, and this code
NSString *path;
if ([[NSFileManager defaultManager] fileExistsAtPath:[[self downloadsDir] stringByAppendingPathComponent:[tableView cellForRowAtIndexPath:indexPath].textLabel.text]]) {
path = [[self downloadsDir] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [tableView cellForRowAtIndexPath:indexPath].textLabel.text]];
}
else{
for (NSString *subdirs in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self downloadsDir] error:nil]) {
BOOL dir;
[[NSFileManager defaultManager] fileExistsAtPath:[[self downloadsDir] stringByAppendingPathComponent:subdirs] isDirectory:&dir];
if (dir) {
for (NSString *f in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[self downloadsDir] stringByAppendingPathComponent:subdirs] error:nil]) {
if ([f isEqualToString:[tableView cellForRowAtIndexPath:indexPath].textLabel.text]) {
path = [[self downloadsDir] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@", subdirs, f]];
}
}
}
}
}
only reads up to one subdirectory, and gives me the path for the file im looking for. I cant find a way better than this to get multiple subdirectories and the paths of the files in those directories. Can anyone help with this? Heres what im trying to do
+Downloads Folder+
+File1+ //I can get the path for this
+Directory1+
+Directory2+
+File3+ // I want to get the path for this, but don't know how
+File2+ // I can get the path for this
I feel like if I just keep repeating the for loop that gets the contents of the directory I might have a problem eventually.
Upvotes: 0
Views: 115
Reputation: 8163
There is a concept called recursion, that is commonly applied to problems like this one. Basically, you call that very method for each of the sub-directories, which in turn, will call it for each of the sub-sub-directories, and so on.
The important thing is that you define a stop point, so it doesn't go on forever. Seems like a good stop point would be a file or an empty directory.
In pseudo-code:
method storePaths(directory)
for each element in directory
if element is a file
store path
else if element not empty directory
call storePaths(element)
Upvotes: 1