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++


基础教程推荐
猜你喜欢
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07