Iterating through files in a folder with nested folders - Cocoa

后端 未结 6 2110
迷失自我
迷失自我 2020-12-07 10:52

I need to access every file in a folder, including file that exist within nested folders. An example folder might look like this.

animals/
 -k.txt
 -d.jpg
 c         


        
6条回答
  •  天涯浪人
    2020-12-07 11:15

    This code worked for me.

    NSMutableString *allHash;  
    
      -(NSString*)getIterate:(NSString*)path {
    
            allHash = [NSMutableString stringWithString:@""];
    
            NSDirectoryEnumerator *de= [[NSFileManager defaultManager] enumeratorAtPath:path];
            NSString *file;
            BOOL isDirectory;
    
            for(file in de)
            {
    
                //first check if it's a file
                NSString* fullPath = [NSString stringWithFormat:@"%@/%@",path,file];
    
                BOOL fileExistsAtPath = [[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDirectory];
                NSLog(@"Check=>%d",fileExistsAtPath);
    
                if (!isDirectory) //its a file
                {
                    //Do with filepath
                }
                else{ //it's a folder, so recurse
                    [self enumerateFolder:fullPath];
                }
            }
    
            return allHash;
    
    
        }
    
        -(void) enumerateFolder:(NSString*)fileName
        {
    
            NSDirectoryEnumerator *de= [[NSFileManager defaultManager] enumeratorAtPath:fileName];
            NSString* file;
            BOOL isDirectory;
    
            for(file in de)
            {
                //first check if it's a file
                BOOL fileExistsAtPath = [[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDirectory];
    
                if (fileExistsAtPath) {
                    if (!isDirectory) //its a file
                    { 
                      //Do with file  
                    }
                    else{ //it's a folder, so recurse
    
                        [self enumerateFolder:file];
                    }
                }
                else printf("\nenumeratefolder No file at path %s",[file UTF8String]);
            }
        }
    

提交回复
热议问题