So I am having trouble reading from a bin file (inside a directory), and storying the contents into an array of structs dynamically. I am getting an error saying "each struct field must be read individually", this is part of the requirements.
Is there an obvious reason I would be having trouble reading the fields. Should I be trying to read them straight into struct stage3 user or create a new array in memory?
Code:
#include <stdio.h>
#include <stdlib.h>
struct stage3
{
double cream;
short int apple;
int brush;
unsigned long finger;
char boy [10];
short int sight;
long int ocean;
unsigned short shovel;
char water;
};
int main(int argc, char** argv)
{
int i;
size_t size;
struct stage3 *user;
FILE *fptr;
if (argc < 2) {
fprintf(stderr, "Usage");
exit(1);
}
if ((fptr = fopen(argv[1], "rb+")) == NULL) {
fprintf(stderr, "could not open file: %s\n", argv[1]);
exit(1);
}
fseek(fptr, 0, SEEK_END);
size = (ftell(fptr));
fseek(fptr, 0, SEEK_SET);
user = malloc(size);
if (user == NULL) {
fprintf(stderr, "memeory exhausted\n");
exit(1);
}
i = 0;
while(1) {
fread(&user.cream, sizeof(int), 1, fptr);
fread(&user.apple, sizeof(double), 1, fptr);
fread(&user.brush, sizeof(int), 1, fptr);
fread(&user.finger, sizeof(short int), 1, fptr);
fread(&user.boy, sizeof(int), 1, fptr);
fread(&user.sight, sizeof(unsigned long), 1, fptr);
fread(&user.ocean, sizeof(char), 10, fptr);
fread(&user.shovel, sizeof(short int), 1, fptr);
fread(&user.water, sizeof(long int), 1, fptr);
if (feof(fptr)) {
break;
i++;
}
fclose(fptr);
free(user);
return 0;
}