您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“C++如何讀寫二進制文件”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!
首先補充函數(shù)open()打開文件流的各種模式:
ios_base::binary 創(chuàng)建二進制文件
ios_base::in 以只讀方式打開文件
ios_base::out 以只寫方式打開文件
ios_base::trunc 重新創(chuàng)建一個文件(即時指定的文件已經(jīng)存在)
ios_base::app 附加到現(xiàn)有文件末尾,而不是覆蓋它
ios_base::ate 切換到文件末尾,但可在文件的任何地方寫入數(shù)據(jù)
以下程序?qū)⒁粋€結(jié)構(gòu)寫入二進制文件并使用該文件的內(nèi)容創(chuàng)建一個結(jié)構(gòu):
#include<fstream>#include<iomanip>#include<string>#include<iostream>using namespace std;struct Human{ Human() { };Human(const char* inName, int inAge, const char* inBirthday) : Age(inAge){ strcpy(Name, inName);strcpy(Birthday, inBirthday);}char Name[30];int Age;char Birthday[20];};int main(){ Human InputData("Steve Hugo", 24, "May 1996"); ofstream myBinaryFile("firstFile.bin", ios_base::out | ios_base::binary);if (myBinaryFile.is_open()){ cout << "Writing one object of Human to a binary file" << endl; myBinaryFile.write(reinterpret_cast<const char*>(&InputData), sizeof(InputData)); myBinaryFile.close();} ifstream myBinaryFile("firstFile.bin", ios_base::in | ios_base::binary);if(myBinaryFile.is_open()){ Human somePerson; myBinaryFile.read((char*)&somePerson, sizeof(somePerson)); cout << "Reading information from binary file:" << endl; cout << "Name=" << somePerson.Name << endl; cout << "Age=" << somePerson.Age << endl; cout << "Birthday=" << somePerson.Birthday << endl;}return 0;}
“C++如何讀寫二進制文件”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。