面试题答案
一键面试实现思路
- 创建一个
NSFileManager
实例,用于文件系统操作。 - 使用
contentsOfDirectoryAtPath:error:
方法获取指定目录下的所有子项(文件和目录)。 - 遍历这些子项,对于每个子项:
- 判断是否是目录,如果是目录,则递归调用遍历方法,继续遍历该子目录。
- 如果是文件,检查其扩展名是否为
.txt
,如果是,则将其路径添加到结果数组中。
代码实现
#import <Foundation/Foundation.h>
NSArray *findTxtFilesInDirectory(NSString *directoryPath) {
NSMutableArray *txtFilePaths = [NSMutableArray array];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *subItems = [fileManager contentsOfDirectoryAtPath:directoryPath error:&error];
if (error) {
NSLog(@"Error accessing directory: %@", error);
return nil;
}
for (NSString *subItem in subItems) {
NSString *subItemPath = [directoryPath stringByAppendingPathComponent:subItem];
BOOL isDirectory;
if ([fileManager fileExistsAtPath:subItemPath isDirectory:&isDirectory]) {
if (isDirectory) {
NSArray *subDirTxtFiles = findTxtFilesInDirectory(subItemPath);
[txtFilePaths addObjectsFromArray:subDirTxtFiles];
} else {
if ([[subItem pathExtension] isEqualToString:@"txt"]) {
[txtFilePaths addObject:subItemPath];
}
}
}
}
return [txtFilePaths copy];
}
你可以使用以下方式调用这个函数:
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *directoryPath = @"/your/directory/path";
NSArray *txtFiles = findTxtFilesInDirectory(directoryPath);
for (NSString *filePath in txtFiles) {
NSLog(@"%@", filePath);
}
}
return 0;
}
请将/your/directory/path
替换为你实际要遍历的目录路径。
注意,在实际应用中,可能需要更完善的错误处理以及对路径合法性的检查等操作。同时,上述代码是基于Objective - C语言实现。如果是在Swift中,实现思路类似,但语法会有所不同。例如在Swift中可以这样实现:
func findTxtFiles(in directoryPath: String) -> [String] {
var txtFilePaths: [String] = []
let fileManager = FileManager.default
do {
let subItems = try fileManager.contentsOfDirectory(atPath: directoryPath)
for subItem in subItems {
let subItemPath = (directoryPath as NSString).appendingPathComponent(subItem)
var isDirectory: ObjCBool = false
if fileManager.fileExists(atPath: subItemPath, isDirectory: &isDirectory) {
if isDirectory.boolValue {
let subDirTxtFiles = findTxtFiles(in: subItemPath)
txtFilePaths.append(contentsOf: subDirTxtFiles)
} else {
if subItem.pathExtension == "txt" {
txtFilePaths.append(subItemPath)
}
}
}
}
} catch {
print("Error accessing directory: \(error)")
}
return txtFilePaths
}
调用方式如下:
let directoryPath = "/your/directory/path"
let txtFiles = findTxtFiles(in: directoryPath)
for filePath in txtFiles {
print(filePath)
}
同样,请将/your/directory/path
替换为实际路径。