【发布时间】:2015-06-04 13:39:11
【问题描述】:
我搜索了类似的帖子,但找不到可以帮助我的帖子。
我正在尝试先写入包含 String 的字符串长度的整数,然后将字符串写入二进制文件中。
但是,当我从二进制文件读取数据时,我读取 value=0 的整数并且我的字符串包含垃圾。
例如,当我输入“asdfgh”作为用户名并输入“qwerty100”作为密码时 我得到两个字符串长度的 0,0,然后我从文件中读取垃圾。
这就是我将数据写入文件的方式。
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 for 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();
在我读取数据的同一个函数的正下方
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();
【问题讨论】:
-
你的阅读方式应该反映你的写作方式。您没有编写长度的字符串表示形式,因此没有理由尝试像那样阅读它。
标签: c++ string binaryfiles