在vs二进制读文件的时候出现了访问权限冲突
如图:
//二进制写文件
#include <iostream>
#include <string>
using namespace std;
#include <fstream>
class Person
{
public:
string m_Name;//性别
int m_Age; //年龄
};
void test0()
{
ofstream ofs;
ofs.open("Person.txt",ios::out|ios::binary);
Person p;
p.m_Name="佳莹";
p.m_Age=18;
ofs.write((const char *)&p,sizeof(p));
ofs.close();
}
int main()
{
test0();
return 0;
}
//二进制读文件
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Person
{
public:
string m_Name;
int m_Age;
};
void test0()
{
ifstream ifs;
ifs.open("Person.txt", ios::in | ios::binary);
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
// cout<<"test";
Person p;
ifs.read((char *)&p, sizeof(p));
cout << p.m_Name << " " << p.m_Age << endl;
ifs.close();
}
int main()
{
test0();
return 0;
}
解决办法:把string改为字符数组 char arr[10];
注意:c写入和读取的时候不要用输入string类型数据,String本身是一个类,包含成员变量和成员函数length(),size()。类强转为char*没有意义,其次string的大小始终为8,不管有多少字符,传入后都只能开辟8字节空间,参数本身就有问题。