So I'm stuck in this piece of code that I'm writing and I want to save data that I receive from a binary file and save it in a array of structure I already tried something but I can't get any good results.
#define MAX_ACCOUNTS 5
#define COUNTER 0
typedef struct t_account {
int id;
char name[50];
char provider[40];
char org[40];
char domain[50];
float balance;
} t_account;
t_account account[MAX_ACCOUNTS];
char *item;
FILE *file_accounts;
char string[0];
int i = COUNTER;
file_accounts = fopen("../accounts.dat", "rb");
if (file_accounts == NULL) {
printf("Error, %s\n", strerror(errno));
exit(1);
} else {
printf("Testing fread() function: \n\n");
//fread(string, sizeof(string), MAX_ACCOUNTS, file_accounts );
while(fgets(string, sizeof(struct t_account), file_accounts )){
printf("%s\n", string);
item = strtok(string, ";");
printf("ID: %i\n", strtol(item,NULL,10));
item = strtok(NULL, ";");
printf("Name: %s\n", item);
item = strtok(NULL, ";");
printf("Provider: %s\n", item);
item = strtok(NULL, ";");
printf("ORG: %s\n", item);
item = strtok(NULL, ";");
printf("Domain: %s\n", item);
item = strtok(NULL, ";");
printf("Balance: %.2f Eur\n", strtof(item, NULL));
i++;
}
}
fclose(ficheiro_contas);
I already tried to save the data inside the while loop like this but for each field in the structure
account[i].id = atoi(item);
but the program crashes in the line that I do that piece of code to "save" the array.
strtok(stringreturns a pointer into string. It does not return a copy.char string[0];is a string of zero length. I certainly is notsizeof(struct t_account). And it does not make sense to readsizeof(struct t_account)chars from the file.char string[512];? And then read the documentation offgets