Search code examples
cbinaryfeof

Output struct objects to binary file and input from it back in C


i write managment system in C. i have this structure

#define STRING_LENGTH 32
typedef struct {
    char name[STRING_LENGTH];
} Name;

typedef struct{
    int id, balance;
    Name clientName;
} Client;

i create few test objects, open binary file for write, use fwrite to write objects to file, closing it and after this using fread into while(!feof... block, and my problem is that i print 4 objects to binary file, and while i read objects from file and print it to screen, last object printed twice. what i do incorrect? i need only to write objects to file and then get them back from it.

my code:

FILE *clientsFile = NULL;

switch (selectedOption)
{
case CLIENT:

        clientsFile = fopen(CLIENTS_FILE_PATH, "wb");

        Client getUser;
        Client temp1 = { 1, 10000, "Alex" };
        Client temp2 = { 2, 100000, "Valery" };
        Client temp3 = { 3, 105466, "Jack" };
        Client temp4 = { 4, 1069640, "Pam" };

        fwrite(&temp1, sizeof(Client), 1, clientsFile);
        fwrite(&temp2, sizeof(Client), 1, clientsFile);
        fwrite(&temp3, sizeof(Client), 1, clientsFile);
        fwrite(&temp4, sizeof(Client), 1, clientsFile);

        fclose(clientsFile);

        clientsFile = fopen(CLIENTS_FILE_PATH, "rb");

        do
        {               
            fread(&getUser, sizeof(Client), 1, clientsFile);
            printf("ID : %d, Name : %s, Balance : %d\n", getUser.id, getUser.clientName.name, getUser.balance);
        } while (!feof(clientsFile));

        break;

output photo : screen of output

thanks for answers


Solution

  • My way is to do it like this. If you read the correct number of records, fine, if not, quit. There is no need to involve feof().

    while(fread(&getUser, sizeof(Client), 1, clientsFile) == 1) {
        printf("ID : %d, Name : %s, Balance : %d\n", getUser.id, getUser.clientName.name, getUser.balance);
    }