檔案型別:
二進位制檔案:檔案以文字的二進位制形式儲存
檔案流類:
ifstream :專用於從檔案中讀取資料
ofstream:專用於向檔案中寫入資料
fstream: 既可寫也可讀,一般使用fstream類,其標頭檔案是fstream.h
使用open函式,open函式是建立檔案流物件和檔案之間的關聯
函式原型
void open (const char* filename , int mode );
引數說明:
filename:要操作的檔案的路徑
絕對路徑:
open(「d:\try.txt」)
相對路徑:
open(「temp\try.txt」);開啟當前資料夾的子資料夾temp中的try.txt
open("…\try.txt");開啟當前資料夾的上一層資料夾中的try.txt
mode:開啟檔案的方式
開啟方式
功能ios::in
開啟檔案用於讀取資料。檔案不存在則開啟出錯
ios::out
開啟檔案用於寫入資料。如果檔案不存在,則新建該檔案,檔案原來就存在,則清除原來內容
開啟檔案,用於在其尾部新增資料。如果檔案不存在,則新建該檔案
ios::ate
開啟乙個已有的檔案,並將檔案讀指標指向檔案末尾。如果檔案不存在,則開啟出錯
ios::trunc
開啟 檔案時清空原來的檔案再寫入
ios:binary
以二進位制的方式開啟
可配合使用,
如:ios::out | ios:binary
使用close函式,close函式只執行切斷檔案流和檔案之間關聯的功能。
函式原型:void close()
即使不手動呼叫close函式,在檔案流物件生命週期結束時,編譯器會先呼叫close函式切斷其與其他檔案的關聯,然後銷毀檔案流函式。但是,為了避免一些不必要的錯誤,open()方式開啟的檔案,一定要手動呼叫close()關閉
文字檔案的讀寫
二進位制檔案的讀寫//文字檔案的寫
fstream out;
out.
open
("..\\trrr.txt"
,ios::out)
;//如果檔案有內容,則清空檔案再寫入檔案if(
!out)
out<<
"name : killer"
<
//按行儲存
out<<
"age : 20"
<
out.
close()
;
out.
open
("..\\trrr.txt"
;//在檔案後面追加寫入內容
out<<
"salary :12000"
<
out.
close()
;//文字檔案的讀
fstream in;
in.open
("..\\trrr.txt"
,ios::in);if
(!in)
string str="";
while
(in>>str)
in.close()
; in.
open
("..\\trrr.txt"
,ios::in)
;while
(getline
(in,str)
) in.
close()
; in.
open
("..\\trrr.txt"
,ios::in)
;char temp[
100]
;while
(in.
getline
(temp,
sizeof
(temp)))
in.close()
;
寫檔案用write函式
函式原型:
ostream& write ( const char * buffer ,int len);
讀檔案用read函式fstream out;
out.
open
("..\\tr.txt"
,ios::out|ios::binary)
;int temp=
1234
; out.
write((
const
char*)
&temp,
sizeof
(temp));
out.
close()
;
函式原型:
istream& read( char * buffer , int len);
fstream in;
in.open
("..\\tr.txt"
,ios::in|ios::binary);if
(!in)
int temp;
in.read((
char*)
&temp,
sizeof
(temp));
cout<
in.close()
;
C 複習(十八)檔案讀寫操作
對檔案的讀寫操作可通過以下三個類來進行 一 file類 string path f fcj haha.txt if file.exists path file.create path file.writealltext path,今天c 複習結束 二 streamwriter streamreade...
Linux(十八)檔案操作
creat函式 close函式 rename函式 remove函式 dup和dup2函式 用於開啟或建立檔案,在開啟或者建立檔案的屬性及使用者許可權等各種引數 inlude intopen const char path,int flags,mode t mode 若成功放回檔案描述符,出錯就返回 ...
C 學習筆記 C 的檔案操作
一 main函式的三個引數 int main int argc,char argv,char envp 1 整型變數int argc,指程式的引數數量,表示在命令列下輸入的時候一共有多少個引數,包括命令 2 字元指標陣列char argv 每個指標指向命令列的乙個字串 3 字元指標陣列char en...