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

Objective-C NSFileHandle 檔案讀寫完整指南

     編輯:關於C語言

NSFileHandle vs NSFileManager

  • NSFileManager:檔案/目錄操作 (建立、刪除、移動、複製、屬性查詢)
  • NSFileHandle:檔案內容讀寫 (開啟、讀取、寫入、定位、截斷、同步、關閉)

核心 API 速查

方法用途
+fileHandleForReadingAtPath:唯讀開啟
+fileHandleForWritingAtPath:唯寫開啟 (截斷現有內容)
+fileHandleForUpdatingAtPath:讀寫開啟
-availableData回傳可讀資料 (至 EOF)
-readDataToEndOfFile從目前位置讀至檔案結尾
-readDataOfLength:讀取指定長度
-writeData:寫入 NSData
-offsetInFile取得目前位移 (unsigned long long)
-seekToEndOfFile移至檔案結尾
-seekToFileOffset:移至指定位移
-truncateFileAtOffset:設定檔案長度 (截斷/擴展)
-synchronizeFile強制寫入磁碟
-closeFile關閉檔案描述符

實戰範例

1. 附加資料到檔案末尾


@autoreleasepool {
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/testfile"];
    NSFileHandle *fh = [NSFileHandle fileHandleForUpdatingAtPath:path];
    [fh seekToEndOfFile];
    NSString *str = @"測試附加資料";
    [fh writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
    [fh closeFile];
}

2. 從檔案中間讀取


NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/testfile"];
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:path];
NSUInteger len = [fh availableData].length;
[fh seekToFileOffset:len / 2]; // 移至中間
NSData *data = [fh readDataToEndOfFile];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
[fh closeFile];

3. 複製檔案內容


NSString *srcPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/testfile"];
NSString *dstPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/outfile"];

[[NSFileManager defaultManager] createFileAtPath:dstPath contents:nil attributes:nil];

NSFileHandle *inFH = [NSFileHandle fileHandleForReadingAtPath:srcPath];
NSFileHandle *outFH = [NSFileHandle fileHandleForWritingAtPath:dstPath];

[outFH writeData:[inFH availableData]]; // 一次性讀寫 (小檔案適用)

[inFH closeFile];
[outFH closeFile];

大檔案分塊複製 (記憶體安全)


const size_t CHUNK = 1024 * 1024; // 1MB
NSFileHandle *in = [NSFileHandle fileHandleForReadingAtPath:srcPath];
NSFileHandle *out = [NSFileHandle fileHandleForWritingAtPath:dstPath];

while (1) {
    NSData *chunk = [in readDataOfLength:CHUNK];
    if (chunk.length == 0) break;
    [out writeData:chunk];
}
[in closeFile];
[out closeFile];

NSData 常用轉換

  • [str dataUsingEncoding:NSUTF8StringEncoding] → NSData
  • [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] → NSString
  • [data bytes] → const void* 原始指標
  • [data length] → 位元組長度

錯誤處理最佳實踐


NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:path];
if (!fh) {
    NSLog(@"無法開啟檔案: %@", path);
    return;
}
@try {
    NSData *data = [fh readDataToEndOfFile];
    // 處理 data
}
@catch (NSException *e) {
    NSLog(@"讀取異常: %@", e.reason);
}
@finally {
    [fh closeFile];
}

進階:非同步檔案 I/O (iOS/macOS)

使用 NSFileHandleReadCompletionNotification、NSFileHandleWriteCompletionNotification 搭配 readInBackgroundAndNotify/writeData:completionHandler: 實現非阻塞讀寫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved