如何使用目标c获取ipad中目录中的所有文件

R. *_*ewi 5 objective-c nsfilemanager ipad ios5

我需要获取目录中的所有文件,包括所有子目录和每个子目录中的所有文件.在目标C中,我尝试使用此方法 [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:nil]

但它只是给我一个目录filePath中的内容文件数组,我不能得到子目录中的所有文件,有人可以帮助我?

谢谢

aru*_*n.s 8

- (void)scanPath:(NSString *) sPath {

    BOOL isDir;

    [[NSFileManager defaultManager] fileExistsAtPath:sPath isDirectory:&isDir];

    if(isDir)
    {
        NSArray *contentOfDirectory=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:sPath error:NULL];

        int contentcount = [contentOfDirectory count];
        int i;
        for(i=0;i<contentcount;i++)
        {
            NSString *fileName = [contentOfDirectory objectAtIndex:i];
            NSString *path = [sPath stringByAppendingFormat:@"%@%@",@"/",fileName];


            if([[NSFileManager defaultManager] isDeletableFileAtPath:path])
            {   
                NSLog(path);
                [self scanPath:path];
            }
        }

    }
    else
    {
        NSString *msg=[NSString stringWithFormat:@"%@",sPath];
        NSLog(msg);
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以调用这个函数来记录目录中的所有文件,希望这会有所帮助.


Jes*_*ers 5

您想使用enumeratorAtURL:includingPropertiesForKeys:options:error:而不是.它默认情况下进行深度枚举:

NSURL *myDirectoryURL = [[NSBundle mainBundle] URLForResource:@"Assets" withExtension:@""];
NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:myDirectoryURL includingPropertiesForKeys:[NSArray array] options:0 errorHandler:^BOOL(NSURL *url, NSError *error) {
    // handle error
    return NO;
}];

NSString *fileOrDirectory = nil;
while ((fileOrDirectory = [directoryEnumerator nextObject])) {
    // use file or directory
}
Run Code Online (Sandbox Code Playgroud)

options参数允许您指定深枚举或浅枚举.

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html