Get the count of files in a directory

江枫思渺然 提交于 2019-11-30 04:23:26

问题


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


回答1:


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




回答2:


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];



回答3:


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."



来源:https://stackoverflow.com/questions/2279565/get-the-count-of-files-in-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!