Get the count of files in a directory

后端 未结 3 698
清酒与你
清酒与你 2021-01-05 06:08

How can I count the files in a directory? I couldn\'t find anything relevant in the class reference of NSFileManager.

相关标签:
3条回答
  • 2021-01-05 06:26

    contentsOfDirectoryAtPath:error: returns an NSArray. Just send count to the array.

    0 讨论(0)
  • 2021-01-05 06:28

    subpathsOfDirectoryAtPath:error: returns an array with all path of target directory include sub-directory.

    But as the document says,"you might not want to use it in performance-critical code."

    0 讨论(0)
  • 2021-01-05 06:33

    contentsOfDirectoryAtPath:error: returns an NSArray of everything in a directory (Files + Folders).

    To get a count of files only, you can filter as follows:

    NSMutableArray *files = [[NSMutableArray alloc] init];
    NSArray *itemsInFolder = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderpath error:NULL];
    
    NSString *itemPath;
    BOOL isDirectory;
    for (NSString *item in itemsInFolder){
        itemPath = [NSString stringWithFormat:@"%@/%@", folderpath, item];
        [[NSFileManager defaultManager] fileExistsAtPath:item isDirectory:&isDirectory];
        if (!isDirectory) {
            [files addObject:item];
        }
    }
    
    return [files count];
    
    0 讨论(0)
提交回复
热议问题