简体   繁体   中英

Using boost to read a binary file into a std::vector?

I have a function that stores a std::vector<uchar> into a binary file, using boost:

void vectorWrite(const string& filename, const std::vector<uchar> dataV)
{

    std::ofstream ofs3(filename, std::ios::out | std::ios::binary);
    boost::archive::binary_oarchive oa3(ofs3);
    oa3 << dataV;
    ofs3.close();

}

This seems to work fine, but I am having trouble reversing the process. This code crashes:

    std::vector<uchar> vectorRead(const string& filename)
    {
        std::vector<uchar> v2;
        std::ifstream ifs(filename);
        boost::archive::binary_iarchive ia(ifs);
        ia >> v2;

       return v2;
    }

I am then running:

std::vector<uchar> dataBack = vectorRead("vector.bin");

Is it not this simple? What am i missing?

Thank you.

What i was missing, was opening the file in binary mode :

std::ifstream ifs(filename);

needed to be:

std::ifstream ifs(filename, std::ios::binary);

So, it becomes

std::vector<uchar> vectorRead(const string& filename)
{
    std::vector<uchar> v2;
    std::ifstream ifs(filename, std::ios::binary);
    boost::archive::binary_iarchive ia(ifs);
    ia >> v2;

    return v2;
}

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