Binary I/O Error

Unhandled exception at 0x5071ad54 (msvcp100d.dll) in BinaryFormatter.exe: 0xC0000005: Access violation writing location 0xfeeefeee.

Sorry, I'm in a hurry. I'm getting a violation for this code:
The code executes normally, and even displays the read values, but then crashes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct Data
{
	int a;
	char b;
	long c;
	string d;
};

int main()
{

	Data writeObj;
	Data readObj;

	writeObj.a = 4;
	writeObj.b = 'd';
	writeObj.c = 57;
	writeObj.d = "STRING";

	ofstream outfile("db.dat", ios::binary);
	outfile.write((char*)&writeObj, sizeof(Data));
	outfile.close();

	ifstream infile("db.dat", ios::binary);
	infile.read ((char*)&readObj, sizeof(Data));
	infile.close();

	cout << readObj.a << endl;
	cout << readObj.b << endl;
	cout << readObj.c << endl;
	cout << readObj.d << endl;
	
	return 0;
}


Thanks.
Data is not trivially copyable because it has a member of type string. It cannot be recreated by reinterpreting it as a char array and filling in some bytes from a file.

Use appropriate I/O, something like outfile << writeObj.a << ' ' << writeObj.b << ' ' << writeObj.c << ' ' << writeObj.d ;
Use appropriate I/O, something like outfile << writeObj.a << ' ' << writeObj.b << ' ' << writeObj.c << ' ' << writeObj.d ;


Wouldn't that specifically be ASCII file output? It looks like he wants binary output, in which case, I'm fairly certain you could get your code working by using a char array with a fixed size, instead of string, no?
Topic archived. No new replies allowed.