Binary file IO error "Unhandled exception at 0x100cad4a...."

Hi, I am learning to use the file streams to handle files. I am stuck with Binary file IO because of this error. I have wrote this small program to showcase the error I am receiving.

This is a program to read data in to an object, write it to a file and then read from the file and display it on the screen.

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
41
42
43
44
45
46
47
48
49
# include <iostream>
# include <conio.h>
# include <fstream>
# include <string>
using namespace std;

class myclass {
	int i;
	string n;
public:
	void accept() {
		cout << "Input name: ";
		cin >> n;
		cout << " Input number: ";
		cin >> i;
	}
	void display() {
		cout << "\nName: " << n;
		cout << "\nNumber: " << i;
	}

} obj;

fstream fiout;

void append() {
	fiout.open("f.txt", ios::out | ios::binary | ios::app );
	obj.accept();
	fiout.write((char*)&obj, sizeof(myclass));
	fiout.close();
}

void show() {
	
	fiout.open("f.txt", ios::in | ios::binary);
	fiout.read((char*)&obj, sizeof(myclass));
	obj.display();
	fiout.close();
}

int main() {
	
	append();
	show();

	_getch();
	return 0;
}


The program runs, accepts data, displays it and when it exits, I get the following error.

"Unhandled exception at 0x100cad4a (msvcp100d.dll) in 26 c binary.exe: 0xC0000005: Access violation reading location 0x00a549f4."

I have stepped through the program and this happens after the last line of the code.

When I remove the ios::app while writing to the file, the error is not there. But I have encountered similar error in programs without ios::app.

I can't understand what I am doing wrong here. Please help!
(I am using Visual Studio 2010)
1
2
fiout.write((char*)&obj, sizeof(myclass));
fiout.read((char*)&obj, sizeof(myclass));


read and write are for raw data buffers only. You should never try to pass complex objects to them (such as a std::string, or your myclass).

What you are doing is dumping the raw binary to a file and reading it back. This doesn't work because string does sorts of magic behind the scenes and this kind of raw i/o totally screws it up.

Instead of doing read/write directly like this, you could make myclass::read / write functions, or you could overload the >> and << operators.

In your function/operator, you would read/write each individual member in an appropriate fashion.
Last edited on
Thanks a lot buddy!
Passing the string like you pointed out seemed to be the problem. Having a string as a member I think made sizeof(myclass) not constant and reading the file based on this I think made the stream go off the bounds. I replaced the string with a constant size char array and all my programs works. Passing the objects as such does not seem to cause any errors as of now. If it becomes a problem, I will try writing the members one my one with a member function like you said. Thanks again!
Topic archived. No new replies allowed.