I am carrying out a small project concerning the management of user data, now I have to create a procedure that must allow reading from a binary file (whose name is passed as a parameter) a list of users.
Dynamic allocation must take place within the subroutine. The file must be opened and closed inside the function. The pointer to the dynamic vector must be assigned to the relevant field of the 'data' parameter as well as the number of elements read.
The function prototype must have this form:void loadData(VD *data, char *namefile);
I have two functions to open and close the file:
FILE * openFile(char *nameFile, char *mode){
FILE *fp = fopen(nameFile, mode);
if(fp == NULL)
exit(-1);
return fp;
}
FILE * closeFile(FILE * fp) {
if (fp != NULL)
fclose(fp);
return NULL;
}
The implementation of the loadData function I made is this:
void loadData(VD *data, char *namefile){
FILE* f = openFile(namefile, "r");
char string[200]; //I don't know what size to give to the string
while(!feof(f)){
fgets(string,200,f);
}
closeFile(f);
}
My doubts are that I don't know how to do dynamic allocation in this case, and I don't even understand what it means: "The pointer to the dynamic vector must be assigned to the relevant field of the 'data' parameter as well as the number of elements read."
Inside the txt file I have a series of people data, here is an example: https://pastebin.com/s4LxFNGE
PS This is VD:
typedef struct{
RecordSubj *v; //RecordSubj is a structure that contains all the data of a subject, the same ones that are present in the link I put above
int nElements;
} VD;
This is the implementation of RecordSubj
typedef struct {
char name[SIZE_NAME + 1];
char surname[SIZE_SURNAME + 1];
int height;
float weight;
char eyeColor[DIM_COLOR];
char hairColor[DIM_COLOR];
hair hairLength;
_Bool beard;
_Bool scar;
char key[DIM_KEY];
char lives[SIZE_LIVES + 1];
GPSPosition position;
StateOf state;
} RecordSubj;
Can you help me?