I am attempting to create a binary .dat file so i attempted this by
#include<stdio.h>
struct employee {
char firstname[40];
char lastname[40];
int id;
float GPA;
};
typedef struct employee Employee;
void InputEmpRecord(Employee *);
void PrintEmpList(const Employee *);
void SaveEmpList(const Employee *, const char *);
int main()
{
Employee EmpList[4];
InputEmpRecord(EmpList);
PrintEmpList(EmpList);
SaveEmpList(EmpList, "employee.dat");
return 0;
}
void InputEmpRecord(Employee *EmpList)
{
int knt;
for(knt = 0; knt < 4; knt++) {
printf("Please enter the data for person %d: ", knt + 1);
scanf("%d %s %s %f", &EmpList[knt].id, EmpList[knt].firstname,EmpList[knt].lastname, &EmpList[knt].GPA);
}
}
void PrintEmpList(const Employee *EmpList)
{
int knt;
for(knt = 0; knt < 4; knt++) {
printf("%d %s %s %.1f\n", EmpList[knt].id, EmpList[knt].firstname,EmpList[knt].lastname, EmpList[knt].GPA);
}
}
void SaveEmpList(const Employee *EmpList, const char *FileName)
{
FILE *p;
int knt;
p = fopen(FileName, "wb"); //Open the file
fwrite(EmpList, sizeof(Employee), 4, p); //Write data to binary file
fclose(p);
}
I give it the input:
10 John Doe 64.5
20 Mary Jane 92.3
40 Alice Bower 54.0
30 Jim Smith 78.2
So the printf statement works and prints the correct information to the screen but the employee.dat file that is created is just random symbols. The file does not currently exist so the program is creating it.