MST

星途 面试题库

面试题:Objective-C利用NSFileManager遍历目录并筛选特定类型文件

假设你有一个目录路径,要求使用NSFileManager遍历该目录及其所有子目录,找出所有扩展名为'.txt'的文件,并将这些文件的路径存储到一个NSArray中。请详细说明实现思路并写出代码。
50.2万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 创建一个NSFileManager实例,用于文件系统操作。
  2. 使用contentsOfDirectoryAtPath:error:方法获取指定目录下的所有子项(文件和目录)。
  3. 遍历这些子项,对于每个子项:
    • 判断是否是目录,如果是目录,则递归调用遍历方法,继续遍历该子目录。
    • 如果是文件,检查其扩展名是否为.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替换为实际路径。