segfault when reading binary file

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();


And this is the code that reads:
1
2
3
4
5
6
7
8
ifstream inFile;
char adr[kMaxString];
cout << endl << "Adr:\t";
cin >> adr;
inFile.open(adr, ios::in | ios::binary);
inFile.seekg(0);
inFile.read((char *)&blocks, sizeof(Datablock)*3);
inFile.close();


Very crude and silly code, I know, but it's just for getting to know file io better. What am I doing wrong here?
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.
Topic archived. No new replies allowed.