File Fiasco

Started by
0 comments, last by basement 18 years, 3 months ago
Prof: Cpp(DevCpp), hey everyone, my ? today is about an issue Im having with saving a class object to a file named data.dat using the write() function. here is the class I want to save(its akward, but its for a calendar basically):
 
class cData//This would hold everydays data
{
   public:
      int a;
      int b;
      int c;
};

class cDay
{
      public:
      cData Data;
};

class cMonth
{
      public:
      cDay Day[30];
};

class cYear
{
      public:
      cMonth Month[11];
};

And here is the code I am using to save it to and retrieve it from a file. This entire file is a test, so disregard the pointlessness of saving and then loading right after.

//init
std::ofstream cgfile;
std::ifstream cgfilein;
cYear ThisYear;// my massive structure for holding all the data by date



ThisYear.Month[0].Day[2].Data.a = 5;//put a random value in an arbitrary date

//write to file
cgfile.open("data.doc",std::ios::binary);
cgfile.write((char*)&ThisYear,sizeof(ThisYear));
cgfile.close();

//read from same file and put data back into ThisYear Class object
cgfilein.open("data.doc",std::ios::binary);
cgfilein.read((char*)&ThisYear,sizeof(ThisYear));
cgfilein.close();

cout << "\n\n" << ThisYear.Month[0].Day[2].Data.a;//when program runs, values should match; should be 5

Here is the Problem: The Code up above represents the first time I run my program. When I enter a value in month and day and then check it later in the code it works fine the first time I run the program. But then when I go back to my code and change the value of the first array(ThisYear.Month[0].Day[2].Data.a = 5;) to something else like this(notice the 7): ThisYear.Month[0].Day[7].Data.a = 5; Everything changes. Specifically, I rerun it and when it gets to the cout portion of the code, it displays some really random #(eg. 369498). I do not understand why when I change a value in a different place, it screws up all my other values elsewhere. Here is a brief context of what my program should do if you need it: I'd like to load this file "data.dat" in the beginning of my program to show values on the right dates. When the user uses the program he changes these values and whatnot. At the end of the program I would like to save the changes and new entries to data.dat.all the values are held in the giant class (the one above). hope this helps as always, any and all help is greatly appreciated.
-CG
Advertisement
A compiler might decide to add extra padding bytes to your structures or classes, for memory alignment reasons. In the case of your cData class, the compiler might add an extra of 4 dummy bytes so that the memory is aligned to 16 bytes (a power of two). This is not a problem unless you read or write the block of memory to disk.

If you're using gcc or MSVC++ you can wrap the "#pragma pack" directive around your class definition and it should work.

This topic is closed to new replies.

Advertisement