C++二進位制方式讀檔案
阿新 • • 發佈:2021-02-05
二進位制方式讀檔案主要利用流物件呼叫成員函式read
函式原型:
istream& read(char*buffer,int len);
引數解釋:字元指標buffer指向記憶體中一段儲存空間。len是讀寫的位元組數。
程式碼示例:
#include <iostream>
#include <fstream> //標頭檔案包含
using namespace std;
//二進位制檔案 寫檔案
class Person
{
public:
char m_Name[64]; //姓名
int m_Age; //年齡
};
void test01()
{
//1.包含標頭檔案
//2.建立流物件
ifstream ifs;
//3.開啟檔案 判斷檔案是否開啟成功
ifs.open("person.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout<<"開啟檔案失敗"<<endl;
return;
}
//4.讀檔案
Person p;
ifs.read((char *)&p, sizeof(Person));
cout << "姓名:" << p.m_Name << " 年齡:" << p.m_Age << endl;
//5.關閉檔案
ifs.close();
}
int main()
{
test01();
return 0;
}