在我的代码中,我首先将姓名和手机号码存储在一个对象中,然后使用 fstream.write() 方法将该对象写入一个文本文件。它成功地工作,但是当我将写入的内容读入另一个对象并调用显示方法时,它会正确显示数据,但是在打印数据后却给了我分段错误。这是我的代码 -
#include<iostream>
#include<fstream>
using namespace std;
class Telephone
{
private:
string name="a";
int phno=123;
public:
void getTelephoneData()
{
cout<<"Enter Name:";
cin>>name;
cout<<"Enter Phone Number:";
cin>>phno;
}
void displayData()
{
cout<<"Name\t\tPhone no"<<endl;
cout<<name<<"\t\t"<<phno<<endl;
}
void getData() {
Telephone temp;
ifstream ifs("Sample.txt",ios::in|ios::binary);
ifs.read((char*)&temp,sizeof(temp));
temp.displayData();
}
};
int main()
{
Telephone t1;
t1.getTelephoneData();
cout<<"----Writing Data to file------"<<endl;
ofstream ofs("Sample.txt",ios::out|ios::binary);
ofs.write((char*)&t1,sizeof(t1));
ofs.close();
t1.getData();
}
Run Code Online (Sandbox Code Playgroud)
请帮助我我错的地方。提前致谢...!
我想自己实现二进制序列化,而不使用Boost或任何其他第三方库.
在C++中,实现它的最简单方法是使用ofstream然后通过网络发送二进制文件.但是有没有其他流类可以用作临时缓冲区以避免将文件写入磁盘?
另外,我怎样才能在纯C中实现这一目标?