#include <stdio.h>
#include <stdlib.h>

typedef struct 
{ 
    int id; 
    char pname[20]; 
    char psurname[20]; 
    double salary;
} Person; 


void SaveData() {
	Person jim = {21, "Jim", "Brown", 34657.612};
	Person tom = {11, "Tom", "Red", 24627.17};
	Person mary = {9, "Mary", "Yello", 44127.12};
	
	FILE *fp = fopen ("citizens.dat", "wb"); 
    if (fp == NULL)  { 
        printf("\nError opening file citizens.dat\n"); 
        exit (1); 
    } 
  
    if( fwrite (&jim, sizeof(jim), 1, fp) != 1 ){
        printf("\nError writing data to file citizens.dat\n"); 
        exit (1); 
    }   
     
    if( fwrite (&tom, sizeof(Person), 1, fp) != 1 ){
        printf("\nError writing data to file citizens.dat\n"); 
        exit (1); 
    }   

    if( fwrite (&mary, sizeof(Person), 1, fp) != 1 ){
        printf("\nError writing data to file citizens.dat\n"); 
        exit (1); 
    }   
    
    fclose(fp);
}


void ReadData()
{
	FILE *fp = fopen ("citizens.dat", "rb"); 
    if (fp == NULL)  { 
        printf("\nError opening file citizens.dat\n"); 
        exit (1); 
    } 

    Person temp;
    
	int n = 0;    
    while(fread( &temp, sizeof(Person), 1, fp) == 1) {
       printf ("%d) id = %d name = %s \t surname = %s \tsalary = %lf\n", ++n, temp.id, temp.pname, temp.psurname, temp.salary); 
   }

   printf("\nThe file contains %d records.\n", n);
   fclose(fp);
}

int main(int argc, char *argv[]) {
	
    SaveData();
    ReadData();
	return 0;
}
