Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(20pt) This question uses almost the same file format as in Quiz 6 that we solve

ID: 3906749 • Letter: #

Question

(20pt) This question uses almost the same file format as in Quiz 6 that we solved in class. But this time, instead of reading and summarizing the data from the input file, we would like to create a dynamic data structure to store all the information about the employees in the memory for further analysis. Suppose the employee data file (say emp.txt) is now starting with an integer showing the number of employees in the file. It then contains that many lines, which are formatted as in Quiz 6. So the file has the followings in each line per employee: helshe worked, and how many hours he/she worked in each day. All these values are integers employee ID, how many days Here is a sample file with 3 employees: 11 4 582 13 10 244 3543 524 15 2 67 Complete the following program that can read emp.txt file and create the dynamic structure as shown in the below figure. There is no output file. ID NumD hours EIU 13 10 2 4 4 3 5 4 3 5 2 4 E[2] 152 #include / suppose all the other standard libraries are included here as well typedef struct t int ID; int int NumD *hours ; /* a dynamic array to store # of hours this employee worked in each day.*/ empT;

Explanation / Answer

#include <stdio.h>

#include <stdlib.h>

typedef struct{

int ID;

int NumD;

int *hours;

} empT;

int main(void)

{

FILE *infp;

int NumEmp, ID, NumD, hour;

int i, j;

empT *E;

/* Open the emp.txt file for reading &

if open operation fail program will be terminated */

if ( (infp = fopen("emp.txt", "r") ) == NULL) {

printf("Input file cannot be opened ");

return -1;

}

/* Read number of employees from file */

if(fscanf(infp, "%d", &NumEmp) != 1) exit(0);

/* Allocate the memory dynamically for storing data of 'NumEmp' numbers of employees */

E = (empT*) malloc(NumEmp * sizeof(empT));

i = 0;

while(i < NumEmp)  

{

fscanf(infp, "%d%d", &ID, &NumD); /* Reading employee ID and number of days worked from file */

(E+i) -> ID = ID; /* Stores employee ID into dynamic structure */

(E+i) -> NumD = NumD; /* Stores number of days 'NumD' into dynamic structure */

  

/* Allocate the memory dynamically for storing 'NumD' number of hours worked in each day */

(E+i) -> hours = (int*) malloc(NumD * sizeof(int));

j=0;

while( j < NumD)

{

fscanf(infp, "%d", &hour); /* Reading number of hours worked from file */

(E+i) -> hours[j] = hour; /* Stores number of hours worked in dynamic array of dynamic structure */

j++;

}

i++;

}

fclose(infp); /* close file */

return(1);

}