Search code examples
carraysstructfwrite

Created file has nothing in it


So I am suppose to make my program be persistent when opened and closed I assume I have to do this with a file, the program is a payroll program that uses structs. 2 Questions here 1. When it comes to this type would binary files be easier? I hear txt files are complicated but not sure why. 2. Here is my code it runs without error but when I go to the file nothing is written inside. These are my two structs

typedef struct{
    int day;
    int month;
    int year;
}DATE;

typedef struct{
    char name[100];
    int age;
    float hrsWorked;
    float hrlyWage;
    float regPay;
    float otPay;
    float totalPay;
    DATE payDate;

}PAYROLL;

and the code

void backUp(PAYROLL employee[], long int *pCounter)
{
    FILE *record = fopen_s(&record, "c:\\record.bin", "wb");
    if (record != NULL){
        fwrite(employee, sizeof(PAYROLL), 1, record);
        fclose(record);
    }

employee has stuff in its structs so I know its not empty if some one could explain the parameters for fwrite that'd be great!


Solution

  • You seem to be mixing up the usage of the longtime-standard fopen() function with the usage of the new-in-C11 fopen_s() function. The latter returns an error code, not a stream pointer. You are overwriting the stream pointer it sets via the first argument with that error code.

    If the program successfully opens the file, it returns 0. After setting that as the value of record, record compares equal to NULL (in Microsoft's C implementation), so you don't even attempt to write. If you caught that case and printed a diagnostic, then you would have had a clue (albeit a misleading one).

    You should do this:

    void backUp(PAYROLL employee[], long int *pCounter)
    {
        FILE *record;
        errno_t result = fopen_s(&record, "c:\\record.bin", "wb");
    
        if (result == 0) {
            fwrite(employee, sizeof(PAYROLL), 1, record);
            fclose(record);
        }
        /* ... */
    }