首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Objective-C 文件系統操作:目錄遍歷與枚舉器用法

     編輯:關於C語言

Objective-C 文件系統操作:目錄遍歷與枚舉器用法

NSFileManager 是 Foundation 框架中文件系統操作的核心類。本文演示兩種目錄遍歷方式:遞歸枚舉器(enumeratorAtPath:)與淺層列表(contentsOfDirectoryAtPath:)。

一、核心 API 對比

方法遍歷深度返回類型適用場景
enumeratorAtPath:遞歸(子目錄)NSDirectoryEnumerator深度掃描、查找文件
contentsOfDirectoryAtPath:僅當前目錄NSArray列表展示、非遞歸需求

二、完整代碼演示

#import 

int main(int argc, const char *argv[]) {
    @autoreleasepool {
        NSFileManager *fm = [NSFileManager defaultManager];
        
        // 1. 獲取當前工作目錄
        NSString *cwd = [fm currentDirectoryPath];
        NSLog(@"當前目錄: %@", cwd);
        
        // 2. 遞歸枚舉器遍歷
        NSDirectoryEnumerator *dirEnum = [fm enumeratorAtPath:cwd];
        NSString *path;
        NSLog(@"=== 遞歸枚舉 ===");
        while ((path = [dirEnum nextObject]) != nil) {
            NSLog(@"%@", path);
        }
        
        // 3. 淺層列表
        NSArray *shallow = [fm contentsOfDirectoryAtPath:cwd error:NULL];
        NSLog(@"=== 淺層列表 ===");
        for (path in shallow) {
            NSLog(@"%@", path);
        }
        
        // 4. 指定路徑列表 (家目錄)
        NSArray *home = [fm contentsOfDirectoryAtPath:@"/Users/fansunion" error:NULL];
        NSLog(@"=== 家目錄 ===");
        NSLog(@"%@", home);
    }
    return 0;
}

三、運行輸出分析

2015-11-29 13:02:49.528 FilePath[2750:159478] 當前目錄: /Users/fansunion/Library/Developer/Xcode/DerivedData/FilePath-dfjiajapcipfrbcbfjmxijqhscws/Build/Products/Debug
2015-11-29 13:02:49.534 FilePath[2750:159478] === 遞歸枚舉 ===
FilePath
2015-11-29 13:02:49.534 FilePath[2750:159478] === 淺層列表 ===
FilePath
2015-11-29 13:02:49.535 FilePath[2750:159478] === 家目錄 ===
(
    ".bash_history",
    ".CFUserTextEncoding",
    ".DS_Store",
    ".ssh",
    ".subversion",
    ".Trash",
    Desktop,
    Documents,
    Downloads,
    Library,
    Movies,
    Music,
    Pictures,
    Public
)

關鍵觀察

  • Xcode 構建產物目錄極深,currentDirectoryPath 指向產物而非源碼目錄
  • 遞歸枚舉器在該目錄下僅發現 1 個文件(可執行文件)
  • 家目錄 /Users/fansunion 展示典型 macOS 用戶目錄結構
  • 點文件(. 開頭)默認包含在列表中

四、進階用法:文件屬性獲取

// 在枚舉器中獲取文件詳細信息
NSDictionary *attrs = [dirEnum fileAttributes];
NSFileType type = [attrs fileType];
NSUInteger size = [attrs fileSize];
NSDate *modDate = [attrs fileModificationDate];
BOOL isDir = (type == NSFileTypeDirectory);

五、常見操作封裝建議


六、錯誤處理最佳實踐

  • 始終傳遞 NSError ** 參數捕獲失敗原因
  • 檢查返回值 nil 而非異常(Foundation 不拋出異常)
  • 權限不足、路徑不存在、IO 錯誤均通過 NSError 返回

七、總結

  • 遞歸枚舉器適合「查找」、「統計」等需遍歷子樹的場景
  • 淺層列表適合 UI 列表展示、非遞歸業務
  • 路徑操作優先使用 NSString 路徑方法(stringByAppendingPathComponent: 等)而非手動拼接
  • 沙盒機制限制 App 只能訪問自身容器目錄,家目錄需用戶授權或命令行工具
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved