我搜索了类似的帖子,但找不到对我有帮助的内容。
我试图先写入包含字符串长度的整数,然后将字符串写入二进制文件。
然而,当我从二进制文件中读取数据时,我读取的是值=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();
最佳答案
读回数据时,您应该执行如下操作:
int result;
file.read(reinterpret_cast<char*>(&result), sizeof(int));
这会将字节直接读入 result
的内存中,不会隐式转换为 int。这将首先恢复写入文件的确切二进制模式,从而恢复您的原始 int
值。
关于c++ - 在二进制文件中写入/读取字符串-C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30645365/