Hello. I'm a newbie in C++ file management. I've got a std::list of pointers to objects of my own class (std::list<MyCl ass*>;). Inside my class, there are some strings, ints and methods. I need to save this list into a file, but I don't know how. I've tried fwrite() and WriteFile(), but no results. Could anyone tell me how to save this list into a file? And if I have to use one of these functions, how do I take memory size of my list?
How to write std::list into a file?
Collapse
X
-
You have to define how to write out a single object using the stream operator as jabbah suggests.
Once you have done this you can output the entire contents of the list using a simple loop with an iterator or using the for_each algorithm.
It is a simple and elegant solution.
There is no "saveList" command, since the list can contain any data type there is no way such a command would be able to know how to output the data.Comment
-
This may not work as well as you think.Code:out << x.a << " " << x.b ..... ;
True, the data will go out to the stream but inoreder to read it back in later, the reader will need to know the exact format that the datawas written with.
That is, you will probably need to devise a record layout for your disc file and write entire records at a time. That way the reader, knowing the record layout, can read in a record.
You might consider converting data types like int to strings and writing out the string. You might set the string to a fixed length so that all ints are written using the same number of chars. That's so thr reader can read that number of chars into a string and convert the string back to an int.Comment
-
OK, I get it now. If there's no way to write list directly into file, I have to write its elements separately, one by one. I did so and it works, when I have to read the list from the file, I just create new objects, give them data from file and create a new list of them. Just thought that there was simpler way.
Thank you.Comment
-
Often to make C++ simple some work has to be done to achieve that.
In the case of objects being written to disc, research the concept of serialization. That is, the ability to convert an object into a serial data stream and also to take a serial data stream an convert it back to an object.
Then research the Visitor design pattern. There is an article about this in the C++ Insights. Here you design a class to accept a Visitor class. It is the Visitor class that serializes the original class. This avoids building serialization into every class. You see, today you want to serialize to disc. Tomorrow you want to decompose your object into a SQL table. If you have your serialization logic inside the class, that class will nee do be changed every time there is a change in the serialization requirements. The Visitor class avoids this. To serialize in a new way you just invent a new Visitor class and use its objects to serialize the original class objects.Comment
Comment