Solved

Writing a whole class to a file

Posted on 2007-03-25
5
203 Views
Last Modified: 2012-05-05
Hello,

I am trying to output a whole class to a file using fstream objects and everything works fine. The only problem is when the class has a member of type vector: I output the class to a file successfully, then I read it back from the file and print out every member of the class to see if it read everything ok, and it outputs everything correctly, EVEN the elements of the vector, but when the program reaches the end of its code and tries to exit, I hear the sound of an error but I don't see a message window saying what the error is and even when I debug the code it doesn't send me to a breakpoint. It just hangs there doing nothing. This is my code

#include <fstream>
#include <iostream>
#include <vector>
using namespace std;

class simple{
public:
      int a;
      int b;
      char* name;
      vector<int> vec;

      simple(){};
      virtual ~simple(){vec.clear();}
};

void saveTo(const char *fileName, simple *obj)
{

      ofstream fout(fileName, ios::binary);
      fout.write((char *)(obj), sizeof(*obj));
      fout.close();

}

void readFrom(const char* fileName, simple *obj)
{
      ifstream fin(fileName, ios::binary);
      fin.read((char *)(obj), sizeof(*obj));
      fin.close();
}

void main()
{
      simple *s = new simple;
      s->a = 1;
      s->b = 2;
      s->name = "something";
      s->vec.push_back(5);
      s->vec.push_back(6);

      simple *si = new simple;

      saveTo("file.dat", s);
      readFrom("file.dat", si);
      cout << si->a << "\n" << si->b <<  "\n" << si->name << "\n";
      for (int i=0; i<si->vec.size(); i++)
      {
            cout << si->vec[i] << "\n";
      }
      delete s;
      delete si;
}

Any ideas why this is happening?
0
Comment
Question by:silethunde
  • 2
  • 2
5 Comments
 
LVL 3

Expert Comment

by:Darrylsh
ID: 18790152
You are saving the char* and not the name "something".  You need to use a char array and not just a pointer.  yoo then need to "serialize" you class and save each element separately, making sure you output the array and not just the pointer.
0
 
LVL 3

Assisted Solution

by:Darrylsh
Darrylsh earned 60 total points
ID: 18790187
One more thing to note, your program seems to be working because the write and read is in the same program and so just happens to be pointing at the same thing, but if instead you had  a separate read and write program you would clearly see it does not work properly.
0
 

Author Comment

by:silethunde
ID: 18790203
When I don't have vectors in the class everything works fine. I don't think the problem is the char* name I have there. Also as I said when I read the values back from the file into a new class and I output the results on screen, everything is fine again. The only problem is the vector there.
0
 

Author Comment

by:silethunde
ID: 18790221
And I guess you might be right about the program working when read and write is in the same program, but why does the vector cause the program to crush?
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 65 total points
ID: 18792582
>>>> I don't think the problem is the char* name
You are wrong. You can't store pointers to a file and expect that these are valid when you read thenm back. Same happens with std::vector. It internally has a pointer to the array what means when you store std::vector you didn't store the int values but only a pointer. All that can work as long as you make storing and reading back in one function cause the pointers are still valid. If you create a new object for restore it will get the same pointers from the file that already where owned (and deleted at end) by an other vector instance what makes it crash.

What to do:

You can use fixed size arrays both for char strings and int array. Then your binary store would write the values rather than pointers and it works.

Or do what Darryish told you: serialize all members - means store size and values in case of vector and store the string contents including the terminating zero char in case of char* - and read back same way. Unfortunately that can't be done with one write/read but member for member only.

Regards, Alex
0

Featured Post

ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ASP.net build a IF/Then Walkthrough Guide 1 215
Need some help with Microsoft Visual Studio C++ 2003 5 61
sorting efficency of sorting algorithm 30 113
Unable to start eclipse ? 17 142
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question