[英]c++ read and write struct array with std::string into binary file
[英]Read/Write struct containing string property to binary file
我在读取/写入具有复杂数据(特别是字符串)的结构时遇到问题。 我的结构如下所示。
struct MyRecord {
char name[80];
string location; // <<== note this
double balance;
unsigned long account_num;
};
我使用不同的功能进行读写。
这是我用来将数据写入文件的代码
struct MyRecord acc;
strcpy(acc.name, "R");
acc.location = "newlocation ok"; // <<== note this
acc.balance = 1.3;
acc.account_num = 34;
ofstream outbal("balance", ios::out | ios::binary);
outbal.write((char *) &acc, sizeof(struct MyRecord));
就像我使用下面的代码从文件读取一样。
ifstream inbal("balance", ios::in | ios::binary);
inbal.read((char *) &acc, sizeof(struct MyRecord));
当我编译时,它可以很好地编译,但是在执行时,我收到了大量错误消息
./binaryfile_3[0x8048f6a]
./binaryfile_3[0x8048e38]
./binaryfile_3[0x8048e54]
/lib/libc.so.6(__libc_start_main+0xe6)[0x148d26]
./binaryfile_3[0x8048aa1]
======= Memory map: ========
00132000-002c3000 r-xp 00000000 fd:00 918500 /lib/libc-2.12.so
// continues....
虽然,它可以在以下两个条件下工作。
string location
我是c ++的新手,我尝试使用手册进行编写,但最终出现错误。 我搜索了几种解决方案,并且在添加string
属性时都以错误告终。 上面的脚本也是我从网站上获取的。 我只是修改了它以匹配我的问题,即它具有不同的功能来读取/写入和构造具有string
请帮助我指出问题所在。 谢谢。
添加这两个功能
std::ostream & operator << ( std::ostream & os, const MyRecord & rec ) {
os.write( rec.name, sizeof( rec.name ) );
size_t sz = rec.location.size();
os.write( & sz, iszeof( sz ) );
os.write( rec.location.c_str(), sz );
os.write( (char*) & balance, sizeof( rec.balance ) );
os.write( (char*) & account_num, sizeof( rec.account_num ) );
return os;
}
std::istream & operator >> ( std::ostream & is, MyRecord & rec ) {
is.read( rec.name, sizeof( rec.name ) );
size_t sz;
is.read( & sz, iszeof( sz ) );
rec.resize( sz );
if ( sz != 0 ) {
is.read( & rec.location[ 0 ], sz );
}
is.read( (char*) & balance, sizeof( rec.balance ) );
is.read( (char*) & account_num, sizeof( rec.account_num ) );
}
这是一种用法
ofstream outbal("balance", ios::out | ios::binary);
outbal << acc;
ifstream inbal("balance", ios::in | ios::binary);
inbal >> acc;
这与Boost.Serialization的手工制作相似性差 。 确实,最好使用boost,而不是我的车辆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.