c++ - 在二进制文件中写入/读取字符串-C++

标签 c++ string binaryfiles

我搜索了类似的帖子,但找不到对我有帮助的内容。

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

然而,当我从二进制文件中读取数据时,我读取的是值=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/

相关文章:

c - 我的删除函数删除了错误的结构记录

c - 如何在 C 中从二进制文件(使用 ab+)读取后打印结构成员

c++ - 在 C 中使用英特尔 TBB

c# - C++ 中是否有等效的 C# SecureString?

c++ - OCCI联动: Undefined symbols

c++ - C++/Qt - 内存分配如何工作?

java - 将填充空格插入字符串

java - 如何使用索引将字符替换为字符串

html - 搜索特定代码字符串

io - 将数字以二进制格式写入lua文件中