NSFileManager 遍历目录

时间:2023-03-10 00:59:39
NSFileManager 遍历目录

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *documentPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

// 遍历目录

// 1.获取指定目录下的文件和目录,不遍历其下的子目录

NSArray *fileArray1 = [[NSArray alloc]init];

fileArray1 = [fileManager contentsOfDirectoryAtPath:documentPath error:nil];

NSLog(@"fileArray1 = %@", fileArray1);

// 2. 枚举器 遍历指定目录下的文件和子目录,遍历其下的子目录

NSDirectoryEnumerator *directoryEnum = [fileManager enumeratorAtPath:documentPath];

NSString *filePath;

while (filePath = [directoryEnum nextObject]) {

NSLog(@"filePath = %@", filePath);

}

// 3.遍历指定目录下的文件和子目录,遍历其下的子目录

NSArray *fileArray3 = [fileManager subpathsAtPath:documentPath];

NSLog(@"fileArray3 = %@", fileArray3);

// 4.同3

NSArray *fileArray4 = [fileManager subpathsOfDirectoryAtPath:documentPath error:nil];

NSLog(@"fileArray4 = %@", fileArray4);