字串,字典,陣列寫入本地檔案和從本地檔案讀取

2021-06-25 19:54:15 字數 2098 閱讀 3091

一.字串,字典,陣列儲存到本地檔案

字串,陣列,字典儲存到本地檔案過程一樣,只是要儲存的資料型別不同而已,這裡以字串儲存到本地檔案為例,如下

nsstring

*content =

@"將字串儲存到本地檔案";

(1)獲取

documents

資料夾路徑

引數:(1)指定資料夾,(2)設定查詢域,(3)是否使用詳細路徑

nsstring

*documentspath = [

nssearchpathfordirectoriesindomains

( nsdocumentdirectory

, nsuserdomainmask

, yes

) firstobject];

(2)拼接上要儲存的檔案路徑

(前面自動加上

/),如果沒有此檔案系統會自動建立乙個

nsstring

*newfielpath = [documentspath

:@"aa.txt」];

(3)將內容儲存到指定檔案路徑

nserror

*error =

nil;   

字串寫入本地檔案引數:(1)要儲存內容的檔案路徑,(2)是否使用原子特性,(3)儲存格式

bool

issucceed = [content

writetofile

:newfielpath

atomically

:yes

encoding

:nsutf8stringencoding

error

:&error];

二.字串,字典,陣列,從本地檔案讀取

字串,字典,陣列從本地檔案讀取的過程一樣,只是要讀取的資料型別不同而已,這裡以從本地檔案讀取字串為例,如下

1.獲取讀取檔案的路徑

(1)獲取

documents

資料夾路徑

nsstring

*documentspath = [

nssearchpathfordirectoriesindomains

( nsdocumentdirectory

, nsuserdomainmask

, yes

) firstobject];

(2)拼接上要儲存的檔案路徑

(前面自動加上

/),如果沒有此檔案系統會自動建立乙個

nsstring

*newfielpath = [documentspath

:@"aa.txt」];

(3)讀取資料

nserror

*error =

nil;(

最後也可以

&error)   

nsstring *content = [nsstring stringwithcontentsoffile:newfielpath encoding:nsutf8stringencoding error:

nil]

三.總結

檔案讀寫暫時只支援

,nsstring

,nsarray

,nsdictionary,nsdata

以及他們的子類

寫入檔案方法

:writetofiel:

物件呼叫方法

讀取檔案

:每個類自帶的能夠根據檔案路徑讀取檔案的方法

:[類名

+ withcontentoffiel],如下

nsstring

:[nsstring stringwithcontentoffile:]

nsarry

:[nsarry arraywithcontentoffiel:]

nsdictionary

:[nsdictionary dictionarywithofcontentfile:]

二進位製流

:[nsdata datawithofcontentfiel:] 

對於nsarray

,nsdictionary

,這種容器

,內部成員也必須是能夠實現檔案讀寫的八個類之一

字串寫入到json檔案

背景 php產生公告 傳送到cgi 在cgi把該公告的json 字串寫入到檔案內 轉義後的字串 通過 jsoncpp 操作 int write notice to json string str path,const string str content std string json file w...

字串和字串陣列

字串陣列 include int main int argc,const char ar printf name1 s n name1 name1 zhangsan 部分初始化中,沒有被初始化的元素預設是0,0 對應的ascii值是 0 char name2 9 printf name2 s n n...

字串和字串陣列和 0

c語言中字串為什麼要有 0呢?0在字串中的作用是什麼 0 在字串中標誌著結尾 用來判斷這個字串已經結束 如果不新增 0 系統就在記憶體中一直向後讀,直到讀到 0 為止 這個情況就造成錯誤 乙個語句結束了,就用分號 表示結束 首先要區分,字元,字元陣列,字串的區別。字串預設的最後會有 0 char k...