获取目录中的文件计数

时间:2021-11-15 23:02:35

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

如何计算目录中的文件?我在NSFileManager的类引用中找不到任何相关内容。

3 个解决方案

#1


14  

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

contentsOfDirectoryAtPath:error:返回NSArray。只需将计数发送到数组。

#2


3  

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

contentsOfDirectoryAtPath:error:返回目录(Files + Folders)中所有内容的NSArray。

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


0  

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

subpathsOfDirectoryAtPath:error:返回一个数组,其中包含目标目录的所有路径包含子目录。

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

但是正如文档所说,“你可能不想在性能关键代码中使用它。”

#1


14  

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

contentsOfDirectoryAtPath:error:返回NSArray。只需将计数发送到数组。

#2


3  

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

contentsOfDirectoryAtPath:error:返回目录(Files + Folders)中所有内容的NSArray。

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


0  

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

subpathsOfDirectoryAtPath:error:返回一个数组,其中包含目标目录的所有路径包含子目录。

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

但是正如文档所说,“你可能不想在性能关键代码中使用它。”