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)