This is c language and I have a file which I want to read it tothis array of poi
ID: 3612774 • Letter: T
Question
This is c language and I have a file which I want to read it tothis array of pointers to structure. I have 2 doctors and 2patients I want to read it to the structure, so this is how itis:#include<stdio.h>
struct doctors
{
char firstname[20];
char lastname[20];
int operationid;
};
struct patients
{
char firstname[20];
char lastname[20];
int chosendocid;
struct doctors*ptr[3];
};
void recursivealloc_mem(FILE *notefile, struct patients, intrec);
int main(void)
{
FILE *notefile;
struct patientshosp;
int rec=3;
notefile =fopen("file1.dat", "r");
if(notefile == NULL)
{
printf("file1.dat file does not exist ");
return(-1);
}
recursivealloc_mem(FILE *notefile, struct patients, int rec);
fclose(notefile);
}
And the file I have is written:
void recursiveallocdoc_mem(FILE *notefile, struct clinic *xhosp,int rec)
{
int index, xindex =1;
if(xindex <= rec)
recursiveallocdoc_mem(rec - 1);
xhosp->doc[rec] = malloc(3 * sizeof( struct doctor));
}
And the file I have is written:
James
Warren
3542
Maud
Spearman
2267
Ike
Williams
2267
Caleb
Walker
3542
I am trying to let the program read and store it by allocate memoryrecursively, that's the one it's giving me problems because I don'tunderstand array of pointers to structures very well. So please howcan I recursively allocate memory for it?
Explanation / Answer
intrec=3;
notefile =fopen("file1.dat", "r");
if(notefile == NULL)
{
printf("file1.dat file does not exist ");
return(-1);
}
recursiveallocdoc_mem(notefile,doc_list,0);
recursivealloc_mem(notefile,hosp, 0);
fclose(notefile);
for(i=0;i<2;i++)
{
printf("Patient %d: Patient name:%s %s doctor = %s %s withoperationid=%d ",i+1,hosp[i]->firstname,hosp[i]->lastname,
hosp[i]->ptr->firstname,hosp[i]->ptr->lastname,hosp[i]->ptr->operationid);
}
system("pause");
}
void recursiveallocdoc_mem(FILE *notefile, struct doctors **xhosp,int rec)
{
char str[20];
struct doctors*hosp;
if(rec < 2){
hosp = (struct doctors*)malloc(sizeof( struct doctors));
fgets((hosp)->firstname,20,notefile);
fgets((hosp)->lastname,20,notefile);
fgets(str,20,notefile);
hosp->operationid = atoi(str);
*xhosp = hosp;
recursiveallocdoc_mem(notefile,xhosp+1,rec+1);
}
}
void recursivealloc_mem(FILE *notefile, struct patients **xhosp,int rec)
{
char str[20];
struct patients *hosp;
inti;
if(rec < 2){
hosp = (struct patients*)malloc(sizeof(structpatients));
fgets((hosp)->firstname,20,notefile);
fgets((hosp)->lastname,20,notefile);
fgets(str,20,notefile);
hosp->chosendocid = atoi(str);
for(i=0;i<2;i++)
if(doc_list[i]->operationid == (hosp)->chosendocid )
(hosp)->ptr = doc_list[i];
*xhosp = hosp;
recursivealloc_mem(notefile,xhosp+1,rec+1);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.