Trouble writing/reading struct array in a binary file in C

  Kiến thức lập trình

I am trying to make a program that stores the name, employee number and salary of employees in a database, where I have to then store the amount of employees along with all the information of each employee (name, number, salary). I need to store the information in a binary file named “EMPLOYEE.DAT”. The function PersistEmployees() runs at the end of the program when the user is finished putting employee information, and is the one that stores the information. There is another function named RestoreEmployees(), which I will explain later. Both functions are in a separate file.

Here is PersistEmployees();

void PersistEmployees(struct Employees employees[], int numOfEmployees)
{
    FILE* fout;
    fout = fopen("EMPLOYEE.DAT", "wb+");

    if (!fout)
    {
        fprintf(stderr, "Error opening file EMPLOYEE.DATn");
        exit(1);
    }

    fwrite(&numOfEmployees, sizeof(numOfEmployees), 1, fout);
    fwrite(employees, sizeof(struct Employees) * numOfEmployees, 1, fout);

    fclose(fout);
}

Here is a screenshot of the “EMPLOYEE.DAT” file that gets created

Then, when the program runs again, “EMPLOYEE.DAT” is to be read, and the program gets the number of employees, stored in an int variable, and the information of each employee, which is stored in a struct array. The function, named RestoreEmployees, takes one parameter, a struct array, and returns the number of employees read.

Here is RestoreEmployees();

int RestoreEmployees(struct Employees employees[])
{
    int employeesInDatabase = 0;

    FILE* fin;
    fin = fopen("EMPLOYEE.DAT", "rb+");

    if (!fin)
    {
        return 0;
    }

    fread(&employeesInDatabase, sizeof(int), 1, fin);
    fclose(fin);

    return employeesInDatabase;
}

The number of employees gets returned properly, 1 when there is only 1 stored, 2 when there is 2, but the struct array is just a jumble of random characters.

Here is the struct that stores the information:

struct Employees
{
    int employeeNumber;
    char name[100];
    double salary;
};

I’m currently thinking it’s something with reading the file, but I’m not sure. Please don’t be too harsh as reading and writing files in c is very confusing to me lol.

New contributor

DeePyson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT