【发布时间】:2014-09-27 19:03:00
【问题描述】:
我想从一个包含vector<int> 的类中创建一些对象,并且我想将该对象保存在一个文件中并下次从该文件中读取,但程序没有正确读取新对象中的类数据那个班的。
例如,它可以读取我的向量的大小(即 500),但它无法读取向量单元格的值!有时,当我的文件包含几个或更多对象时,程序会终止并且不打印任何内容。
class my_class {
int counter;
vector<int> v;
public:
my_class():counter(0),v(500,0){}
void fill_vec(int x) {
v.at(counter++)=x;
}
const vector<int> & get_vec () const {
return v;
}
const my_class & operator=(const my_class &inp){
v=inp.v;
counter=inp.counter;
return *this;
}
};
void write_to_file(my_class x) {
fstream opf("/home/rzz/file/my_file.dat", ios::in |ios::out|ios::binary); // my file has been created before - no problem to creat file here
opf.seekp(0,ios::end);
opf.write(reinterpret_cast < char *> (&x),sizeof(my_class));
}
my_class read_from_file(int record_number){
my_class temp;
fstream opf("/home/rzz/file/my_file.dat", ios::in |ios::out|ios::binary);
opf.seekg(record_number*sizeof(my_class), ios::beg);
opf.read(reinterpret_cast< char *> (&temp),sizeof(my_class));
return temp;
}
int main() {
my_class zi;
zi.fill_vec(15);
write_to_file(zi);
my_class zi2=read_from_file(0);
vector<int> vec;
vec=(zi2.get_vec());
cout<<zi2.get_vec().size();// right answer , print 500 correctly
cout<<"first element of vector ( should be 15 ) : "<<vec.at(0);//print 0 here , that is wrong
return 0;
}
谁能帮帮我?
【问题讨论】:
标签: c++ class serialization vector randomaccessfile