//=================================================================== // Matt Kretchmar // A simple program illustrating // - nested structs // - malloc and free // - tokenizer with strtok //=================================================================== #include #include #include typedef struct exam_t { float grade; float bonuspoints; } Exam_T; typedef struct homework_t { int score; struct homework_t *next; } Homework_T; typedef struct student_t { char name[20]; Exam_T *exams; Homework_T *homeworks; } Student_T; int main ( int argc, char *argv[] ) { int i,j,n; char *filename; if ( argc >= 2 ) filename = argv[1]; else filename = "students.txt"; // Open the data file for reading FILE *fp = fopen(filename,"r"); if ( !fp ) { printf("Error opening file [%s]\n",filename); exit(1); } // Read n from file. Create an array of n students. Student_T *class; fscanf(fp,"%d\n",&n); class = (Student_T *) malloc ( sizeof(Student_T) * n ); // read the set of 3 exams for each student char buffer[200]; for (i = 0; i < n; i++ ) { fgets(buffer,200,fp); printf("Processing student %d: %s\n",i,buffer); char *s = strtok(buffer," \t\n"); strcpy(class[i].name,s); printf("\tName: %s \t",class[i].name); class[i].exams = (Exam_T *) malloc (sizeof(Exam_T) * 3); for (j = 0; j < 3; j++ ) { char *score = strtok(NULL," \t\n"); class[i].exams[j].grade = atof(score); class[i].exams[j].bonuspoints = 0; printf("(%4.1f) \n",class[i].exams[j].grade); } } // You might have a part here that reads in the variable number // of homeworks into a linked list // free the exam memory for (i = 0; i < n; i++ ) { free(class[i].exams); } // free the student array free(class); // close the file fclose(fp); return 0; } /* Sample data file below 2 Mary 82 70 88 50 77 83 80 Tom 65 88 92 100 90 56 */