I'm trying to get into binary file io. I have written a smiple class consisting of an int and a string. Writing this to a binary file seems to work fine(allthough I wont know for sure until I can open the file), but reading the file causes the program to segfault.
Here's the code that writes:
1 2 3 4 5 6 7 8 9 10 11 12 13
string in;
for (int i = 0; i < 3; i++) {
cin >> in;
Datablock d(rand()%10, in);
blocks.push_back(d);
}
ofstream outFile;
outFile.open("data.blocks", ios::out | ios::binary);
outFile.seekp(0);
for (int i = 0; i < 3; i++) {
outFile.write((char *)&blocks[i], sizeof(Datablock));
}
outFile.close();
You probably aren't reading the file structure correctly. If you aren't reading the chunks at the right size or at the right address then it will return a segmentation fault. Take a look at the file structure of the file you are trying to read and make sure you are reading it correctly, reading binary files are needs to be handled on a file-type to file-type basis because they are structured differently.