Writing/Reading 二进制文件中的字符串-C++

Writing/Reading strings in binary file-C++

我搜索了类似的 post 但找不到可以帮助我的东西。

我正在尝试先写入包含字符串长度的整数,然后将字符串写入二进制文件。

然而,当我从二进制文件中读取数据时,我读取了值=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();
file.write(reinterpret_cast<const char *>(&usernameLength),sizeof(int));

这从 &usernameLength; 中写入 sizeof(int) 个字节;这是整数的二进制表示,取决于计算机体系结构(小端与大端)。

atoi(intBuffer))

这会将 ascii 转换为整数并期望输入包含字符表示。例如intBuffer = { '1', '2' } - return 12.

你可以试着按照你写的方式来阅读它-

*(reinterpret_cast<int *>(&intBuffer))

但它可能会导致未对齐的内存访问问题。最好使用像JSON这样的序列化格式,这将有助于以跨平台方式阅读它。

读回数据时,您应该执行如下操作:

int result;
file.read(reinterpret_cast<char*>(&result), sizeof(int));

这会将字节直接读入 result 的内存中,不会隐式转换为 int。这将首先恢复写入文件的确切二进制模式,从而恢复您的原始 int 值。