c++二进制读写文件
首先要包含头文件
fstream
或istream
、ostream
下面是全部代码演示
#include<iostream>
#include<string>
/*首先要包含这个头文件*/
#include<fstream>
using namespace std;
class Person
{
public:
char m_Name[64];//姓名
int Age;//年龄
};
void test01(void)
{
ofstream ofs("test01.txt",ios::out|ios::binary);
Person p = { "王爷",1231 };
//接收参数类型为const *char,所以取Person的地址值让char指针接收,强转类型
ofs.write((const char*)&p,sizeof(Person));
ofs.close();
}
void test02(void)
{
ifstream ofs("test01.txt", ios::in | ios::binary);
Person p;
ofs.read((char*)&p, sizeof(Person));
cout << p.m_Name << p.Age << endl;
}
int main()
{
test02();
return 0;
}