简体   繁体   English

将向量写入和读取为二进制文件

[英]Writing and reading vector into binary files

I have a vector: 我有一个向量:

class Element
{
public:

    string pathName;
    ui64 offsitePtr;
    ui64 subPage;

public:

    Element(void);

    ~Element(void);
};

vector<Element> elem;

The size of elem will be controlled less than 4096 bytes. elem的大小将被控制为小于4096字节。 At the end of the program, I should fwrite elem into a binary file. 在节目的最后,我应该fwrite elem成一个二进制文件。 The solution I'm using currently is to make a char buffer and write the element in elem in it. 我当前正在使用的解决方案是制作一个char缓冲区并将元素写入其中的elem中。 I don't think it is a good idea. 我认为这不是一个好主意。 Is there any other good ideas? 还有其他好主意吗?

Provided you don't write the vector or the Element s directly from memory, it's okay. 只要您不直接从内存中写出vector或Element ,就可以了。 You'll need to serialize anything that isn't POD (plain old data). 您需要序列化不是POD的任何内容(纯旧数据)。 That is in your case: vector and string . 在您的情况下: vectorstring

The vector is easy, because you can just make a function for Element . 向量很容易,因为您可以为Element创建一个函数。 But you probably want to serialize the vector size: 但是您可能想要序列化向量大小:

ofstream& WriteVec( ofstream& s, vector<Element> &elem )
{
    size_t size = elem.size();
    s.write( (char*)&size, sizeof(size) );
    for( int i = 0; i < size; i++ )
        elem(i).Write(s);
    return s;
}

For your element: 对于您的元素:

ofstream& Element::Write( ofstream& s )
{
    // Serialize pathName
    size_t strsize = pathName.size();
    s.write( (char*)&strsize, sizeof(strsize) );
    s.write( pathName.c_str(), strsize );

    // Serialize other stuff
    s.write( (char*)&offsitePtr, sizeof(offsitePtr) );
    s.write( (char*)&subPage, sizeof(subPage) );
}

And you do something similar when you read. 当您阅读时,您也会做类似的事情。 Will leave you to work that out =) Note in each case, you're writing a size, and then the data. 将使您无法解决=)请注意,在每种情况下,您都在写一个大小,然后写数据。 When you read, you read in the size, then resize your structure before reading the contents into it. 阅读时,您会读入大小,然后在读取内容之前调整结构的大小。

Oh, and make sure you open the file stream in binary mode. 哦,请确保您以二进制模式打开文件流。

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

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