简体   繁体   中英

Creating multiple txt files to store data in c++

I have an array of objects each object has some data members in it.All i want do is create a file for each object to store data.Is this possible? For example i have an array of 10 objects data of the first object must be stored in data01.txt data of second object must is stored in data02.txt and etc (same format of filename used in the example is not required any filename is OK). Thanks in advance.

You have to write just one function:

std::string serializeObject(const XClass &object);

Which will represent object's data as a string. And then write serialized objects to files routinely:

std::ofstream outFile;

for (...
    outFile.open(sFileName);
    outFile << serializeObject(..

Your question is a little lacking in detail, but I'm assuming that you want to save your class objects, which are in an array, to disk.

If that understanding is correct, then the solution wouldn't seem to hard.

I would recommend using boost::serialize for saving your classes to disk ( http://www.boost.org/doc/libs/1_54_0/libs/serialization/doc/index.html )

As for your iteration process, here is an example that might help:

#include <string>
#include <vector>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_array.hpp>

class PrettyPetunia
{
public:
    PrettyPetunia(){;}
    ~PrettyPetunia(){;}
private:
    std::string _myName;
};

typedef boost::shared_ptr<PrettyPetunia> PrettyPetuniaPtr;
typedef std::vector<PrettyPetuniaPtr>    PrettyPetunias;
typedef PrettyPetunias::iterator         PrettyPetuniasItr;

void SaveClassObjectOutToDisk(const char* fileName, PrettyPetuniaPtr classObjectToSave);

void IterateArrayToSaveToDisk(PrettyPetunias& petunias)
{
    unsigned int loopCounter = 0;
    for (PrettyPetuniasItr itr = petunias.begin(); itr != petunias.end(); ++itr )
    {
        boost::scoped_array<char> fileName ( new char[1024] ); // 1024 or PATH_MAX, your choice
        sprintf(fileName.get(), "data%d02.txt", loopCounter);
        PrettyPetuniaPtr ptr = (*itr);
        SaveClassObjectOutToDisk(fileName.get(), (*itr) );
    }
}


void SaveClassObjectOutToDisk(const char* fileName, PrettyPetuniaPtr classObjectToSave)
{
    // ...
}

If you're interested in using there file for various web applications, you can use JSON format: http://en.wikipedia.org/wiki/Json

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

Boost and Poco both can handle this format foe example.

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