File I/O (serialization) with character shift
May 2, 2015 at 8:40pm UTC
My issue is that with my serialization set up the way it is, my fields are bleeding together so that when I read it in from the file into the class, I'm getting multiple fields in one of my class variables.
I can't seem to figure out what I'm doing wrong. Any suggestions?
Output to file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
void key_pair::WriteClass(std::ofstream& file)
{
std::string * str[4] = {&pass, &old_pass, &name, &exclude};
unsigned len;
char convert;
int shift = rand() % 128;
std::stringstream tmp;
file.write(reinterpret_cast <const char *>(&shift), sizeof (shift));
for (int i = 0; i < 4; ++i){
for (std::string::iterator j = (*str[i]).begin(); j != (*str[i]).end(); ++j){
convert = *j;
convert += shift;
tmp << convert;
}
len = tmp.str().size();
file.write(reinterpret_cast <const char *>(&len), sizeof (len));
file.write(tmp.str().c_str(), len);
tmp.clear();
tmp.str(std::string());
}
file.write(reinterpret_cast <const char *>(&pass_min), sizeof (pass_min));
file.write(reinterpret_cast <const char *>(&pass_max), sizeof (pass_max));
file.write(reinterpret_cast <const char *>(&flags), sizeof (flags));
}
Input from file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
key_pair::key_pair(std::ifstream& file)
{
unsigned len;
int shift;
char convert;
std::string tmp;
std::stringstream converted;
std::string * str[4] = {&pass, &old_pass, &name, &exclude};
file.read(reinterpret_cast <char *>(&shift), sizeof (shift));
for (int i = 0; i < 4; ++i){
file.read(reinterpret_cast <char *>(&len), sizeof (len));
if (len > 0){
char * buf = new char [len];
file.read(buf, len);
tmp.append(buf, len);
delete [] buf;
}
for (std::string::iterator j = tmp.begin(); j != tmp.end(); ++j){
convert = *j;
convert -= shift;
converted << convert;
}
(*str[i]) = converted.str();
converted.clear();
converted.str(std::string());
}
file.read(reinterpret_cast <char *>(&pass_min), sizeof (pass_min));
file.read(reinterpret_cast <char *>(&pass_max), sizeof (pass_max));
file.read(reinterpret_cast <char *>(&flags), sizeof (flags));
}
May 2, 2015 at 10:04pm UTC
See line 17 in the input code snippet. Do you really want to append?
May 2, 2015 at 10:35pm UTC
*sigh* No. I want to replace. >.<
Topic archived. No new replies allowed.