David Frickert David Frickert - 3 months ago 24
C Question

How can I read two different data types from binary file in C?

I have the following code:

typedef struct{
int user_id;
char username[100];
char password[25];
} User;
int id = 10001;
User array[50];


And then the important part that's failing (writing and reading):

FILE *f = fopen("users.dat", "w");
User aux;
int j = 0;

for(int i = 0; i < 50; i++){
fwrite(&array[i],sizeof(array[i]),1 , f);
fwrite(&id, sizeof(id), 1, f);
f = fopen("users.dat,"r");
while(fread(&aux, sizeof(aux), 1, f)){
array[j++] = aux;
fread(&id, sizeof(id),1 ,f);

Can someone explain me why this doesn't work? AKA why it's reading all the User but it doesn't read the id. I've tried having an int counting the number of users and only printing those but it didn't work as well.
Thanks for the help and i'll post more code if needed.


Your second loop

while(fread(&aux, sizeof(aux), 1, f))

will read the id - moving to the end of the file, so the following read will fail.

If you save to the file how many user record to read back and loop for that number you can get it to work.