简体   繁体   中英

Write the content of an object into a file in C++

I'm using OpenCV, and I am computing the histogram of some images, which is contained inside a class named CvHist. I have a CvHist object, but I want to store it to use it later on in another file. How can I do that?

Thank you

Actually, in OpenCV there is a specific way to do that. You can write an object in an XML file as follow:

 CvFileStorage* storage = cvOpenFileStorage("globalHistogram.xml", 0, CV_STORAGE_WRITE);
 cvWrite(storage, "histogram", global_histogram);

and read is as such:

  CvHistogram* global_histogram;
  CvFileStorage* storage = cvOpenFileStorage("globalHistogram.xml", 0, CV_STORAGE_READ);
  global_histogram = (CvHistogram *)cvReadByName(storage, 0, "histogram" ,0);

The Boost Serialization library is pretty nice. It may do what you want. http://www.boost.org/doc/libs/1_49_0/libs/serialization/doc/index.html

1) Decide on a file format, plan it at the byte level (If an existing format is suitable, prefer it).

2) Write out the data in the file format you decided on.

You can add a method to the class called Serialise , something along the lines of the following:

CvHist::Serialise( std::string fName, bool read )
{
    if ( read )
    {
        std::ifstream fStream( fName );
        // Read in values from file, eg:
        fStream >> this->param1;
        fStream >> this->param2;
        // ...etc
    }
    else
    {
        std::ofstream fStream( fName, ios::trunc ); // (ios::trunc clears file)
        // Read out values into file, eg:
        fStream << this->param1;
        fStream << this->param2;
        // ...etc
    }
}

Note, the order is important - the order that you read the various parameters from the file must match the order you write parameters to the file. Also remember to #include <fstream>

Now, to create a CvHist object populated with data from a file data.txt you can simply write this:

CvHist object;
object.Serialise( "data.txt", true );

If you've populated an object and want to store it in a file, this time, say, bob.dat , write this:

// (object has been populated with data previously)
object.Serialise( "bob.dat", false );

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