I'm writing a c++ program for my school project which involves lots of binary files. My problem is that whenever the compiler encounters a write statement (by this I mean writing data from an object of a class to a binary file using fstream::write), execution stops and I get an abnormal termination message. I'm sure the 'write' statement is the problem because every statement before it gets executed, while the next statements do not. The problem seemed to have been solved when I used fwrite instead, but then I discovered that data was not actually being written into the file. I've tried writing the object into the file in another function or in methods using 'this' pointer, but the computer doesn't seem to accept any of it.
The program was working just fine until a few days ago, but seemingly out of the blue, it's stopped working. I can't attach the source code because the problem is spread throughout the program, which is 5000+ lines long. However, here's a sample of what causes problems:
bottle b; //bottle is a class
fstream file ("Bottle.dat",ios::out|ios::binary);
file.write ((char*)&b,sizeof(b));
As an alternate, I've also tried
FILE*fptr=fopen ("Bottle.dat","w");
fwrite (&b, sizeof(b), 1, fptr);
The former results in abnormal termination, the latter does not work. There are no error messages during compilation. Can anybody help me? I'm a total newbie at programming, though (still in high school), so please try to keep it simple. Thanks!
EDIT: Maybe this will work as better example.
class irrigation
{ int n,i,itime[20],t[20];
float amt[20],water[20];
protected:
float irr;
public:
float getirr()
{ return irr;
}
void irrigate();
};
void irrigate_calc()
{ fstream file ("Irrigate.dat",ios::in|ios::binary);
irrigation i;
file.read ((char*)&i,sizeof(i));
file.close();
i.irrigate();
fstream file1 ("Irrigate.dat",ios::out|ios::binary);
file1.write ((char*)&i,sizeof(i));
file1.close();
}
As far as I can tell, the problem arises when I open a file for reading, close it again and then open it for writing. Of course, I did try directly opening the file in ios::in, ios::out and ios::ate mode together, but that messed things up, big time.
EDIT 2: Another issue the same program is facing is that some normal cout statements intermittently spew out garbage: lots of special characters and little bits from other, totally unrelated cout statements. Any particular reason this is happening?
bottleis a POD type. How isbottledefined? - K-balloI can't attach the source code because <excuse>Always means you didn't create a testcase during your debugging, which means you should not be here asking yet. :) - Lightness Races in Orbit