c++ - Modifying dynamic data like string in binary files -
i have binary file contains records of student each record instance of class student defined as:
class student { string idno, sname; int books_issued; vector<string> bname; public: void save(fstream &of); void load(fstream &inf); void modify_student() { cout<<"id no:\t"<<idno<<"\n"; cout <<"modify student's name:\n"; cout<<"enter name:\t"; cin.ignore(); getline(cin, sname); } //some more code here };
i writing record in file using save member function:
void save(fstream &of) { unsigned len = idno.size(); of.write((char *)&len, sizeof(len)); of.write(idno.c_str(), len); len = sname.size(); of.write((char *)&len, sizeof(len)); of.write(sname.c_str(), len); of.write((char *)&books_issued, sizeof(books_issued)); len = bname.size(); of.write((char *)&len, sizeof(len)); int = 0; while(len>0) { unsigned strlen = bname[i].size(); of.write((char *)&strlen, sizeof(strlen)); of.write(bname[i].c_str(), strlen); i++; len--; } }
and reading records file using load function returns size of record read:
unsigned int load(fstream& inf) { unsigned finallength = 0; unsigned len; inf.read((char *)&len, sizeof(len)); if(len>0) { char *buf = new char[len+1]; inf.read(buf, len); buf[len] = '\0'; idno= buf; delete[] buf; } finallength+=(len+sizeof(len)); inf.read((char *)&len, sizeof(len)); if(len>0) { char *buf = new char[len+1]; inf.read(buf, len); buf[len] = '\0'; sname = buf; delete[] buf; } finallength+=(len+sizeof(len)); inf.read((char *)&books_issued, sizeof(books_issued finallength+=(sizeof(books_issued)); bname.erase(bname.begin(), bname.end()); inf.read((char *)&len, sizeof(len)); finallength+=(len); while(len>0) { unsigned strlen; inf.read((char *)&strlen, sizeof(strlen)); if(strlen>0) { string str; char *buf = new char[strlen+1]; inf.read(buf, strlen); buf[strlen] = '\0'; str = buf; bname.push_back(str); delete[] buf; } finallength+=(strlen+sizeof(strlen)); len--; } return finallength; }
the read , write operations performed successfully, while trying modify records, shows unexpected behaviour:
void modify_specific_student() { string studentid; cout<<"enter id no:\t"; cin>>studentid; fstream fp; fp.open("student.dat", ios::binary|ios::in|ios::out); student st; int found = 0; if(fp.is_open()) { while(!fp.eof()) { unsigned int len = st.load(fp); cout<<"length: "<<len<<"\n"; if(!fp.eof()) { if(st.searchbyidno(studentid)) { st.show_personal_details(); st.modify_student(); unsigned int pos = -1*len; fp.seekp(pos,ios::cur); st.save(fp); cout<<"record updated\n"; found = 1; } } } } fp.close(); if(!found) cout<<"record not found\n"; }
in view, problem arises because new string may of different size , require subsequent data(and records) shifted. if cause, how correct it, or if not,achieve modification of records?
Comments
Post a Comment