1. 程式人生 > >fopen中r+和w+的區別

fopen中r+和w+的區別

r+: Open for reading and writing.  The stream is positioned  at  the beginning of the file.

w+:Open for reading and writing.  The file is created  if  it  does not  exist, otherwise it is truncated.  The stream is positioned at the beginning of the file.

r+具有讀寫屬性,從檔案頭開始寫,保留原檔案中沒有被覆蓋的內容;

w+具有讀寫屬性,寫的時候如果檔案存在,會被清空,從頭開始寫。

r 開啟只讀檔案,該檔案必須存在。 
r+ 開啟可讀寫的檔案,該檔案必須存在。 
w 開啟只寫檔案,若檔案存在則檔案長度清為0,即該檔案內容會消失。若檔案不存在則建立該檔案。 
w+ 開啟可讀寫檔案,若檔案存在則檔案長度清為零,即該檔案內容會消失。若檔案不存在則建立該檔案。 
a 以附加的方式開啟只寫檔案。若檔案不存在,則會建立該檔案,如果檔案存在,寫入的資料會被加到檔案尾,即檔案原先的內容會被保留。 
a+ 以附加方式開啟可讀寫的檔案。若檔案不存在,則會建立該檔案,如果檔案存在,寫入的資料會被加到檔案尾後,即檔案原先的內容會被保留。 
上述的形態字串都可以再加一個b字元,如rb、w+b或ab+等組合,加入b 字元用來告訴函式庫開啟的檔案為二進位制檔案,而非純文字檔案。不過在POSIX系統,包含Linux都會忽略該字元。