Writing/Reading strings in binary file-C++(在二进制文件中写入/读取字符串-C++)
本文介绍了在二进制文件中写入/读取字符串-C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我搜索了类似的帖子,但找不到对我有帮助的帖子。
我正在尝试首先写入包含字符串长度的整数,然后将该字符串写入二进制文件。
但是,当我从二进制文件中读取数据时,我读取值为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++
基础教程推荐
猜你喜欢
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
