iPhone 檔案結構和檔案操作

2021-06-12 01:12:20 字數 2776 閱讀 9494

**:

這篇文章主要是針對沙盒儲存方式的檔案操作,詳文如下:

2、documents 目錄就是我們可以用來寫入並儲存檔案得地方,一般可通過下面的方式得到:

nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes);  

nsstring *documentsdirectory = [paths objectatindex:0];

3、tmp 目錄我們可以在裡面寫入一些程式執行時需要用得資料,裡面寫入得資料在程式退出後會沒有。可以通過 nsstring *nstemporarydirectory(void); 方法得到;

4、檔案一些主要操作可以通過nsfilemanage 來操作,可以通過 [nsfilemanger defaultmanger] 得到它得例項。

a.建立乙個目錄或者檔案:

比如要在documents下面建立乙個test目錄,

nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes);  

nsstring *documentsdirectory = [paths objectatindex:0];

nslog(@」%@」,documentsdirectory);

nsfilemanager *filemanage = [nsfilemanager defaultmanager];

bool ok = [filemanage createdirectoryatpath:mydirectory attributes:nil];

比如要在documents下面建立乙個file.txt:

// 結果為:/documents/file.txt  

b.取得乙個目錄下得所有檔名:

//如上面的mydirectory)可用

nsarray *file = [filemanager subpathsofdirectoryatpath: mydirectory error:nil];

或 nsarray *files = [filemanager subpathsatpath: mydirectory ];

c.讀取某個檔案:

nsdata *data = [filemanger contentsatpath:myfilepath];//myfilepath是包含完整路徑的檔名  

或直接用nsdata 的類方法:

nsdata *data = [nsdata datawithcontentofpath:myfilepath];

d.儲存某個檔案:

//可以用 nsfilemanager的下列方法:  

- (bool)createfileatpath:(nsstring *)path contents:(nsdata *)data attributes:(nsdictionary *)attr;

或 nsdata 的

- (bool)writetofile:(nsstring *)path atomically:(bool)useauxiliaryfile;

- (bool)writetofile:(nsstring *)path options:(nsuinteger)writeoptionsmask error:(nserror **)errorptr;

e.刪除某個檔案:

//可以用 nsfilemanager的下列方法:  

//removes the file or directory at the specified path.

- (bool)removeitematpath:(nsstring *)path error:(nserror **)error

//removes the file or directory at the specified url.

- (bool)removeitematurl:(nsurl *)url error:(nserror **)error

f.移動某個檔案或者重新命名某檔案

//想要重新命名乙個檔案,我們需要把檔案移到乙個新的路徑下。下面的**建立了我們所期望的目標檔案的路徑,

然後請求移動檔案以及在移動之後顯示檔案目錄。

//通過移動該檔案對檔案重新命名

//判斷是否移動

if ([filemanager moveitematpath:filepath topath:filepath2 error:&error] != yes)

nslog(@"unable to move file: %@", [error localizeddescription]);

//顯示檔案目錄的內容

nslog(@"documentsdirectory: %@",[filemanager contentsofdirectoryatpath:documentsdirectoryerror:&error]);

iphone官方sdk用於讀寫資料的方法

我們知道,出於安全考慮,iphone的官方sdk並不能像toolchain一樣隨意寫檔案。

注意:這兩個方法都是儲存在/documents/裡面。

}

iPhone 檔案結構和檔案操作

ps 請大家 ios開發討論qq群 73254416,驗證資訊請填寫 csdn。有什麼問題可以參與交流和討論。不同的存放型別決定了不同的讀取方式和寫入方式。關於儲存型別,請參考另一篇文章 iphone影象儲存的幾種型別以及對應的讀取方法。進行了一下重新編輯和小的修改,與大家共享。自己根目錄下的一些檔...

iPhone 檔案結構和檔案操作

這篇文章主要是針對沙盒儲存方式的檔案操作,詳文如下 3 tmp 目錄我們可以在裡面寫入一些程式執行時需要用得資料,裡面寫入得資料在程式退出後會沒有。可以通過 nsstring nstemporarydirectory void 方法得到 4 檔案一些主要操作可以通過nsfilemanage 來操作,...

iphone檔案操作

如何在iphone os下建立 刪除 讀取 寫入檔案 建立與刪除 建立檔案管理器 nsfilemanager filemanager nsfilemanager defaultmanager 獲取路徑 引數nsdocumentdirectory要獲取那種路徑 nsarray paths nssear...