2010-09-11 70 views
1

有沒有辦法在Objective-C中執行文件處理?我只是想做簡單的讀寫,可以使用'c',但我強迫使用Objective-C類:@。我正在研究NSInputStream,但它已經過去了。有沒有解釋如何使用NSInputStream的任何教程?目標文件處理C

+0

Objective-C是C的一個嚴格的超集。如果你願意,你可以在C中執行文件I/O。 – mipadi 2010-09-11 20:49:23

回答

2

如果你需要做的是真的簡單的I/O,你可以直接告訴一個對象從初始化自身,或本身寫入,文件系統路徑或URL。這適用於幾個基礎類,包括NSString,NSData,NSArray和NSDictionary等。

嘗試通過查看以下兩種NSString的方法開始了:

- initWithContentsOfFile:encoding:error:

- writeToFile:atomically:encoding:error:

+0

謝謝你,這真的很有幫助。 – itsaboutcode 2010-09-11 21:08:44

+0

不客氣,我喜歡基金會的框架和其他原因。:-) – jlehr 2010-09-11 21:36:36

3

我有基本的文件麻煩的i/o當我第一次打它的OBJ-C以及。我結束了使用NSFileHandle獲取C風格訪問我的文件。這裏有一個基本的例子:

// note: myFilename is an NSString containing the full path to the file 

// create the file 
NSFileManager *fManager = [[NSFileManager alloc] init]; 
if ([fManager createFileAtPath:myFilename contents:nil attributes:nil] != YES) { 
    NSLog(@"Failed to create file: %@", myFilename); 
} 
[fManager release]; fManager = nil; 

// open the file for updating 
NSFileHandle *myFile = [NSFileHandle fileHandleForUpdatingAtPath:myFilename]; 
if (myFile == nil) { 
    NSLog(@"Failed to open file for updating: %@", myFilename); 
} 

// truncate the file so it is guaranteed to be empty 
[myFile truncateFileAtOffset:0]; 

// note: rawData is an NSData object 

// write data to a file 
[myFile writeData:rawData]; 

// close the file handle 
[myFile closeFile]; myFile = nil; 
+0

正是我需要的,謝謝! – Kalle 2013-12-15 05:03:28