将包含字符串属性的结构读/写到二进制文件 [英] Read/Write struct containing string property to binary file
问题描述
在读取/写入具有复杂数据(特别是字符串)的结构时遇到问题.我的结构如下所示.
I am running in to an issue while reading/writing a struct having complex data specifically string. my struct looks like below.
struct MyRecord {
char name[80];
string location; // <<== note this
double balance;
unsigned long account_num;
};
我使用不同的功能进行读写.
I use different functions for reading and writing.
这是我用来将数据写入文件的代码
This is the code I am using to write the data to file
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));
就像我使用下面的代码从文件中读取一样.
same like I am using the below code to read from file.
ifstream inbal("balance", ios::in | ios::binary);
inbal.read((char *) &acc, sizeof(struct MyRecord));
当我编译时,它可以很好地编译,但是在执行时,我收到了大量错误消息
when I compile, it compiles nicely, but when executing I am getting the big list of error messages
./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....
尽管如此,它可以在以下两个条件下工作.
although, it works in following 2 conditions.
- 读写功能相同
- 如果我删除
string location
我是C ++的新手,我尝试使用手册进行编写,但最终出现错误.我搜索了几种解决方案,并在添加string
属性时都以错误告终.上面的脚本也是我从网站上获取的.我刚刚对其进行了修改,以匹配我的问题,即具有不同功能的具有string
I am new to c++, I tried writing using the manual and ended up in error. I searched through several solution and all end up in error while adding the string
property. The above script also I grabbed from a site. I just modified it to match my issue which having different function to read/write and struct having string
请帮助我指出问题所在.谢谢.
Please help me to pin point the issue. Thanks.
推荐答案
添加这两个功能
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,而不是我的车辆.
This is poor handmade similarity of Boost.Serialization. Indeed, it would be better to use boost, then my vehicle.
这篇关于将包含字符串属性的结构读/写到二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!