I've been having some issues with the read() and write() functions in C++ for binary file handling of objects. I've been facing issues while reading and writing an Object to a file.
Here is the code. I've tried all kinds of little tweaks here and there, but none appear to have any effect.
#include <iostream>
#include <fstream>
using namespace std;
class Participant {
int ID;
string NAME;
int SCORE;
fstream file;
public:
Participant(const Participant &p) {
this->ID = p.ID;
this->NAME = p.NAME;
this->SCORE = p.SCORE;
}
Participant () {}
Participant(int id, string name, int score) {
ID = id;
NAME = name;
SCORE = score;
}
void input() {
file.open("participant.dat", ios::app | ios::binary);
file.write((char*)this, sizeof(*this));
file.close();
}
void output(int id) {
file.open("participant.dat", ios::in | ios::binary);
Participant p;
while(!file.eof()) {
file.read((char*)&p, sizeof(p));
if (p.ID == id) {
cout << "Match Found" << endl;
cout << "Name: " << p.NAME << endl;
cout << "ID: " << p.ID << endl;
cout << "Score: " << p.SCORE << endl;
file.close();
return;
}
}
file.close();
}
};
//fstream Participant::file;
int main() {
fstream f;
f.open("participant.dat", ios::out);
f.close();
Participant p1(1, "Sam", 200);
Participant p2(2, "Bob", 100);
p1.input();
p2.input();
p1.output(2);
//Participant::output(1);
}
The output appears correctly, however, it crashes right afterwards. Through the use of "Cout" statements I was able to deduce that it crashes right after the output() method.
The error code my IDE (codeblocks) gives me, -1073740940 (0xC0000374).
If there's someone who knows what the problem is, and how to solve it, help would be greatly appreciated.
Update:
Thanks to some debugging, and some of the comments, I figured out the problem. You need to use character arrays instead of strings.
User contributions licensed under CC BY-SA 3.0