c++ - 结构填充

扫码查看

我正在尝试将文件中的数据块直接读取到结构中,但是填充导致读取的数据过多和数据未对齐。

我是否必须手动将每个部分读入结构,还是有更简单的方法来做到这一点?

我的代码:

结构

typedef unsigned char byte;

struct Header
{
    char ID[10];
    int  version;
};

struct Vertex //cannot rearrange the order of the members
{
    byte    flags;
    float   vertex[3];
    char    bone;
    byte    referenceCount;
};

我如何读取数据:
std::ifstream in(path.c_str(), std::ifstream::in | std::ifstream::binary);

Header header;
in.read((char*)&header.ID, sizeof(header.ID));
header.ID[9] = '\0';
in.read((char*)&header.version, sizeof(header.version));
std::cout << header.ID << " " << header.version << "\n";
in.read((char*)&NumVertices, sizeof(NumVertices));
std::cout << NumVertices << "\n";

std::vector<Vertex> Vertices(NumVertices);

for(std::vector<Vertex>::iterator it = Vertices.begin(); it != Vertices.end(); ++it)
{
    Vertex& v = (*it);
    in.read((char*)&v.flags, sizeof(v.flags));
    in.read((char*)&v.vertex, sizeof(v.vertex));
    in.read((char*)&v.bone, sizeof(v.bone));
    in.read((char*)&v.referenceCount, sizeof(v.referenceCount));
}

我尝试做:in.read((char*)&Vertices[0], sizeof(Vertices[0]) * NumVertices);,但是由于我认为是填充,所以这会产生不正确的结果。

另外:目前,我正在使用C样式强制转换,在这种情况下使用的正确C++强制转换是什么?或者C样式强制转换可以吗?

最佳答案

如果您要用二进制形式写出整个结构,则无需像分别存储每个变量一样读取它。您只需将结构的大小从文件读入已定义的结构即可。

Header header;
in.read((char*)&header, sizeof(Header));

如果您始终在同一体系结构或同一台机器上运行,则无需担心字节序问题,因为将它们写成应用程序需要读取它们的方式即可。如果您正在创建文件,在一种架构上,并希望它在另一种架构上可移植/可用,那么您将需要相应地交换字节。我过去这样做的方法是创建自己的交换方法。 (例如Swap.h)
Swap.h - This is the header you use within you're code

void swap(unsigned char *x, int size);

------------------

SwapIntel.cpp - This is what you would compile and link against when building for Intel

void swap(unsigned char *x, int size)
{
    return;   // Do nothing assuming this is the format the file was written for Intel (little-endian)
}

------------------

SwapSolaris.cpp -  This is what you would compile and link against when building for Solaris

void swap(unsigned char *x, int size)
{
    // Byte swapping code here to switch from little-endian to big-endian as the file was written on Intel
    // and this file will be the implementation used within the Solaris build of your product
    return;
}

关于c++ - 结构填充,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5804541/

10-11 22:38
查看更多