Writing/Reading strings in binary file-C++ -
i searched similar post couldn't find me.
i' m trying first write integer containing string length of string , write string in binary file.
however when read data binary file read integers value=0 , strings contain junk.
for example when type 'asdfgh' username , 'qwerty100' password 0,0 both string lengths , read junk file.
this how write data file.
std::fstream file; file.open("filename",std::ios::out | std::ios::binary | std::ios::trunc ); account x; x.createaccount(); int usernamelength= x.getusername().size()+1; //+1 null terminator int passwordlength=x.getpassword().size()+1; file.write(reinterpret_cast<const char *>(&usernamelength),sizeof(int)); file.write(x.getusername().c_str(),usernamelength); file.write(reinterpret_cast<const char *>(&passwordlength),sizeof(int)); file.write(x.getpassword().c_str(),passwordlength); file.close();
right below in same function read data
file.open("filename",std::ios::binary | std::ios::in ); char username[51]; char password[51]; char intbuffer[4]; file.read(intbuffer,sizeof(int)); file.read(username,atoi(intbuffer)); std::cout << atoi(intbuffer) << std::endl; file.read(intbuffer,sizeof(int)); std::cout << atoi(intbuffer) << std::endl; file.read(password,atoi(intbuffer)); std::cout << username << std::endl; std::cout << password << std::endl; file.close();
when reading data in should following:
int result; file.read(reinterpret_cast<char*>(&result), sizeof(int));
this read bytes straight memory of result
no implicit conversion int. restore exact binary pattern written file in first place , original int
value.
Comments
Post a Comment