写文件:
#includeusing namespace std; #include class Person { public: char m_sName[64]; int m_nAge; }; void main() { Person p{"张三",18}; cout << "姓名:" << p.m_sName << " 年龄:" << p.m_nAge << endl; //1、添加头文件 //2、创建文件流 ofstream ofs("二进制文件.doc", ios::out | ios::binary); //3、打开文件流 并判断是否打开成功 //ofs.open("二进制文件.doc", ios::out | ios::binary); //4、写入数据 ofs.write((const char*)&p, sizeof(Person)); //5、关闭文件流 ofs.close(); }
读文件:
#includeusing namespace std; #include class Person { public: char m_sName[64]; int m_nAge; }; void main() { Person p; //1、包含头文件 //2、创建文件流 ifstream ifs; //3、打开文件流 并判断是否打开成功 ifs.open("二进制文件.doc", ios::in | ios::binary); if (!ifs.is_open()) { cout << "文件打开失败" << endl; } //4、读文件 ifs.read((char*)&p, sizeof(Person)); cout << "名字:" << p.m_sName << " 年龄:" << p.m_nAge << endl; //5、关闭文件流 ifs.close(); }



