简体   繁体   中英

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. At the end of the program, I should fwrite elem into a binary file. The solution I'm using currently is to make a char buffer and write the element in elem in it. 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. You'll need to serialize anything that isn't POD (plain old data). That is in your case: vector and string .

The vector is easy, because you can just make a function for 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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