简体   繁体   English

将结构写入文件

[英]Write struct to file

When I write a struct to file, how the memory sets up in the file? 当我向文件写入结构时,如何在文件中设置内存? For instance this struct and function: 例如,以下结构和功能:

struct vector3D
{
    public:
        float x, y, z;

    vector3D(float modelX, float modelY, float modelZ)
    {
        x = modelX;
        y = modelY;
        z = modelZ;
    }

    vector3D()
    {
        x = 0;
        y = 0;
        z = 0;
    }
}


inline void writeVector3D(vector3D vec, FILE *f)
{
    fwrite((void*)(&vec), sizeof(vector3D), 1, f);
}

And this code in main: 这段代码在main中:

vector3D vec(1, 2, 3);
writeVector3D(vec, file);

How does the information sets up in the file? 文件中的信息如何设置? does it like 123 ? 123吗? Or struct has different set up? 还是struct有不同的设置?

You probably need to read about: 您可能需要阅读以下内容:

  • Data structure alignment ( http://en.wikipedia.org/wiki/Data_structure_alignment ) - for information about how struct members are arranged in memory 数据结构对齐( http://en.wikipedia.org/wiki/Data_structure_alignment)-有关结构成员如何在内存中排列的信息
  • Endianness ( Endianness ) - for information about how single variable arranged in memory 字节序( Endianness )-有关单个变量如何在内存中排列的信息
  • Floating-point representation in memory (can't add third link) - because floating-point variables is much more 'strange' than integer ones. 内存中的浮点表示(不能添加第三个链接)-因为浮点变量比整数变量更“奇怪”。

Data will be written in same order as they are placed in memory, including alignment gaps. 数据将按照它们在内存中的写入顺序进行写入,包括对齐间隙。

It writes it as a sequential binary stream. 它将其写入为顺序二进制流。

The size of the file will be the size of the struct . 文件的大小将为struct的大小

In your case, it would write a total of 12 bytes (4 bytes per float), and it will be structured this way: 在您的情况下,它将总共写入12个字节(每个浮点数4个字节),并且将采用以下方式进行结构化:

  • First 4 bytes would represent the float 1 前4个字节代表浮点数1
  • Second 4 bytes would represent the float 2 后4个字节代表浮点数2
  • Third 4 bytes would represent the float 3 后4个字节代表浮点数3

You need to have preprocessor #pragma pack(1) to byte align the structure otherwise its aligned depending on the processor architecture(32-bit or 64-bit). 您需要具有预处理器#pragma pack(1)以字节对齐结构,否则根据处理器体系结构(32位或64位)对其进行对齐。 Also check this #pragma pack effect 还要检查此#pragma pack效果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM