c++ - 写/读简单二进制文件的奇怪行为
问题描述
我在二进制文件上读写。输出读数时出现小错误。
字符串在那里,但有一些小片段,例如:(I"�U) (�U) 附加到其中约 30% 的末尾
我在 Ubuntu 上使用 g++ 编译器
简化代码:
struct Db_connection
{
public:
string name;
}
int Db_connection::write_config()
{
ofstream config_f("config.dat", std::ios_base::binary | std::ios_base::out); //open file
string str = name;
int size = str.length();
config_f.write(reinterpret_cast<char *>(&size), sizeof(int)); // write size of string in int size chunk
config_f.write(str.c_str(), size); //write string
config_f.close();
return 0;
}
Db_connection read_config()
{
ifstream config_f("config.dat", std::ios_base::binary | std::ios_base::in);
Db_connection return_obj;
int size;
string data;
config_f.read(reinterpret_cast<char *>(&size), sizeof(int)); // read string size
char buffer[size];
config_f.read(buffer, size); // read string
data.assign(buffer);
return_obj.name = data;
return return_obj;
}
有什么明显的我搞砸了吗?这和endian有关系吗?我试图将代码最小化为绝对必需品
实际代码更复杂。我有一个包含 2 个结构的向量的类。1 个结构有四个字符串成员,另一个有一个字符串和布尔值。这些函数实际上是该类的成员并(分别)返回该类。函数循环遍历按顺序写入结构成员的向量。
两个怪事:
- 为了调试,我在 read 和 write 函数的每次迭代中添加了
size
和变量的输出。双方都准确一致。侧面是准确的,但侧面有奇怪的特殊字符。我正在查看以下输出:data
size
data
write
read
Read Size: 12
Data: random addy2�U //the 12 human readable chars are there but with 2 extra symbols
- 最后的数据块(一个布尔值)每次都很好,所以我认为不存在文件指针问题。如果它相关:每一个
bool
都int
很好。它只是字符串的一部分。
希望我犯了一个愚蠢的错误,并且可以批评这个最小化的代码。实际的例子太长了。
解决方案
非常感谢 WhozCraig,
以下编辑确实有效:
Db_connection read_config()
{
ifstream config_f("config.dat", std::ios_base::binary | std::ios_base::in);
Db_connection return_obj;
int size;
string data;
config_f.read(reinterpret_cast<char *>(&size), sizeof(int)); // read string size
vector<char> buff(size);
config_f.read(buff.data(), size);
data = string(buff.begin(), buff.end());
return_obj.name = data;
return return_obj;
}
正如 paddy 直接指出和 WhozCraig 所暗示的那样,这段代码仍然需要实现一个标准化的、可移植的数据类型,以便将整数正确地记录为二进制,并且还需要重新考虑写入函数。
非常感谢你们俩。在编写代码之前,我阅读了 5 到 8 个“cpp 二进制 i/o”的热门搜索结果,但最终还是一团糟。你们救了我几个小时/几天的生命。
推荐阅读
- html - 工具提示的 CSS 可见性规则不起作用
- javascript - 在 Amazon Elastic Beanstalkd 上部署 Javascript Cron 作业和队列
- javascript - $.jAlert 不是函数
- android - 同时使用 fresco 和 MediaPlayer
- javascript - 如何创建 javascript 正则表达式以获取匹配项 {{match}}
- python - Python切片多个输出
- javascript - 离子如何将变量传递给firebase equalTo方法
- ffmpeg - 为什么以下 ffmpeg 命令会输出 11 分钟长的视频?
- roblox - 我正在使用 WeAreDevs 进行 Roblox 漏洞利用,但出现此错误。我的文字有什么问题?(CS1061)
- regex - 正则表达式函数不匹配。如何正确书写