小编Dam*_*n L的帖子

以二进制形式序列化和反序列化向量

我在尝试将矢量(std :: vector)序列化为二进制格式然后正确反序列化并能够读取数据时遇到问题.这是我第一次使用二进制格式(我使用的是ASCII,但现在已经变得难以使用)所以我只用一个整数向量开始简单.

每当我读回数据时,向量总是具有正确的长度,但数据是0,未定义或随机.

class Example  
{  
public:  
    std::vector<int> val;  
};
Run Code Online (Sandbox Code Playgroud)

写:

Example example = Example();  
example.val.push_back(10);  
size_t size = sizeof BinaryExample + (sizeof(int) * example.val.size()); 

std::fstream file ("Levels/example.sld", std::ios::out | std::ios::binary);

if (file.is_open())  
{  
    file.seekg(0);  
    file.write((char*)&example, size);  
    file.close();  
}
Run Code Online (Sandbox Code Playgroud)

读:

BinaryExample example = BinaryExample();

std::ifstream::pos_type size;  
std::ifstream file ("Levels/example.sld", std::ios::in | std::ios::binary | std::ios::ate);

if (file.is_open())  
{   
    size = file.tellg();

    file.seekg(0, std::ios::beg);
    file.read((char*)&example, size);
    file.close();
}
Run Code Online (Sandbox Code Playgroud)

有谁知道我做错了什么或做了什么或能够指出我需要做的方向?

c++ binary file-io vector

4
推荐指数
1
解决办法
2668
查看次数

标签 统计

binary ×1

c++ ×1

file-io ×1

vector ×1