C 檔案操作 文字檔案的讀寫 二進位制檔案的讀寫

2021-10-01 06:01:54 字數 2375 閱讀 2159

1.程式在執行中產生的資料都是臨時資料,程式一旦執行結束會被釋放,可以通過檔案相關的操作將資料持久儲存。

2.檔案型別有文字檔案(檔案以文字的ascll碼形式儲存在計算機中)和二進位制檔案(檔案以文字的二進位制形式儲存在計算機中,使用者一般直接讀不懂他們)。

3.c++中對檔案操作需要包含標頭檔案,涉及到的三大檔案操作類:ofstream寫操作類;ifstream讀操作類;fstream讀寫操作類。

第1步:包含標頭檔案#include

第2步:建立流物件ofstream ofs

第3步:開啟檔案ofs.open("檔案路徑",開啟方式)

第4步:寫檔案ofs<

第5步:關閉檔案ofs.close()

注意:1.檔案的開啟方式

2.開啟方式可以通過|操作符配合使用,如開啟二進位制寫檔案 ios::binary|ios:out

3.建立流物件ofstream也可以選擇fstream讀寫類

案例**

#include using namespace std;

//第1步

#include int main()

第1步:包含標頭檔案#include

第2步:建立流物件ifstream ifs

第3步:開啟檔案ifs.open("檔案路徑",開啟方式)判斷是否開啟成功,開啟方式和上面寫檔案一樣

第4步:讀資料

第5步:關閉檔案ifs.close()

案例**

#include using namespace std;

//第1步

#include void test()

//第4步

char buf[1024] = ;//字元陣列初始化為0

while (ifs >> buf)

//第5步

ifs.close();

}int main()

注意:第4步讀資料方式有四種。其他三種如下

//第二種

char buf[1024] = ;

while (ifs.getline(buf,sizeof(buf)))

//第三種

#include #include using namespace std;

//第1步

#include void test()

//第4步

string buf;

while (getline(ifs,buf))

//第5步

ifs.close();

}int main()

//第四種

#include using namespace std;

//第1步

#include void test()

//第4步

char c;

while ((c=ifs.get())!=eof)

//第5步

ifs.close();

}int main()

1.二進位制方式對檔案操作,開啟方式指定為ios::binary,二進位制檔案不僅可以對內建資料型別的資料操作,還可以對物件型別操作。

2.寫入的二進位制檔案出現亂碼不用處理,只要讀到的正確即可

#include using namespace std;

//第1步 標頭檔案

#include class person ;

void test() ;

ofs.write((const char *)&p,sizeof(p));

//第5步關閉

ofs.close();

}int main()

#include using namespace std;

//第1步

#include class person ;

void test()

//第4步

person p ;

ifs.read((char *)&p,sizeof(p));

cout << p.name << p.age;

//第5步

C C 讀寫文字檔案 二進位制檔案

掌握c語言文字檔案讀寫方式 掌握c語言二進位制檔案讀寫方式 掌握cpp文字檔案讀寫方式 掌握cpp二進位制檔案讀寫方式 1.文字檔案寫入 採用c模式對txt進行寫出 void txtwrite cmode 寫出txt file fid fopen txt out.txt w if fid null ...

C C 讀寫文字檔案 二進位制檔案

掌握c語言文字檔案讀寫方式 掌握c語言二進位制檔案讀寫方式 掌握cpp文字檔案讀寫方式 掌握cpp二進位制檔案讀寫方式 1.文字檔案寫入 採用c模式對txt進行寫出 void txtwrite cmode 寫出txt file fid fopen txt out.txt w if fid null ...

C 實現檔案讀寫(文字檔案和二進位制檔案)

最近因為疫情宅在家,於是又狠下心開始了一直想學,但又一直斷斷續續的c 自學之路。聽的課程是慕課上北大郭煒老師的 程式設計與演算法 三 c 物件導向程式設計 現在每天學一點,一方面為了加強理解,另一方面方便後續的查閱。檔案讀寫的原理,類似於輸入輸出流,只是從鍵盤輸入變為了從檔案輸入 讀檔案 從螢幕輸出...