I wrote a simple program to learn how to use random access filling. It compliles fine but on runtime gives the access violation error. I am only writing and reading a single record.
Header file:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
#ifndef HEADER_H
#define HEADER_H
class info
{
private:
int id;
string name;
public:
info(int = 0, string = " ");
void set(int, string);
void display();
void write();
void read();
};
#endif
Implementation file:
#include<iostream>
#include<string>
#include<fstream>
#include"Header.h"
using namespace std;
info::info(int x, string y)
{
set(x, y);
}
void info::set(int x, string y)
{
id = x;
name = y;
}
void info::display()
{
cout << "\n\n\tid : " << id;
cout << "\n\tname" << name;
}
void info::write()
{
ofstream o("info.dat", ios::out | ios::binary | ios::app);
info a(id, name);
info *p = &a;
o.write(reinterpret_cast<const char *>(p), sizeof(info));
o.close();
cout << "\n\n\tWrite Successful";
}
void info::read()
{
ifstream i("info.dat", ios::in | ios::binary);
i.seekg(0);
info a(0, "a");
info *p = &a;
i.read(reinterpret_cast<char *>(p), sizeof(info));
i.close();
p->display();
cout << "\n\n\tRead Successful";
}
Main:
#include<iostream>
#include<string>
#include<fstream>
#include"Header.h"
using namespace std;
void main()
{
info a(10, "muaaz");
a.write();
a.display();
info b(2, "m");
b.read();
}
The error occurs after the read function. The cout "Read Successful" at the end of the read function runs fine and there is no other statement after that in the main. I dont know what is causing the error.