Binary file read/write

I'm trying to write an object to a binary file and then trying to read it back certain parts but I'm having trouble writing it.

Header file
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
#ifndef H_EMPLOYEE
#define H_EMPLOYEE

#include <iostream>
#include <string>
using namespace std;

#pragma (push)
#pragma pack(1);

class employee
{
public:
	void addRecord();
private:
	int id;
	char lastName[20];
	char firstName[20];
	char social[20];
	float salary;
	int age;
};

#pragma pack (pop)
#endif 


implementation file
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
#include <iostream>
#include <fstream>
#include "employee.h"
using namespace std;

void employee::addRecord()
{
	for(int i=0;i<20;i++)
	{
	lastName[i]='\0';
	firstName[i]='\0';
	social[i]='\0';
	}

	id=1;
	cout<<"Enter first name: "<<endl;
	cin>>lastName;
	cout<<"Enter last name: "<<endl;
	cin>>firstName;
	cout<<"Enter your social security number: Ex. XXX-XXX-XXXX "<<endl;
	cin>>social;
	cout<<"Enter your salary: "<<endl;
	cin>>salary;
	cout<<"Enter your age: "<<endl;
	cin>>age;
	
}


main
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
	employee target;

	target.addRecord();
	cout<<endl;

	ofstream out_file ("example.bin", ios::out|ios::binary|ios::ate);
        out_file.write((char*)&target,sizeof(target));

	out_file.close();

	ifstream in_file ("example.bin", ios::in|ios::binary|ios::ate);

    
	char temp[sizeof(target)];
	in_file.seekg(0,ios::beg);
	in_file.read((char*)&temp,sizeof(target));
    

	for(int i=0;i<sizeof(target);i++)
	{
	cout<<temp[i];
	}
	
	in_file.close();


When i try to read back individual fields from the file i don't get the id,age, or salary. I figure its writing the address of the floats and ints but idk how to fix this or what to do.

Ive tried everything if any one has suggestions they would be appreciated.

Last edited on
The problem you are having is not with reading the data from the file, it's how you print that data after you have read it in. You are printing out the value of the class byte-by-byte, so any fields in your class that have multi-byte types will not be printed correctly (int and float are typically 4 bytes each). Instead of loading the data from the file into an array of chars, try allocating memory for an instance of the employee class, then passing a pointer to that to the read function. Then you can access the members of that class as the appropriate types. Something like this:

1
2
3
employee empFromFile;
in_file.read((char*)&empFromFile, sizeof(employee));
cout << empFromFile.id; //etc.. 
Topic archived. No new replies allowed.