Advertisement
Guest User

Untitled

a guest
Jul 1st, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.16 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. struct Student
  6. {
  7.     char *name;
  8.     int fac_num;
  9.     double avg_grade;
  10. };
  11.  
  12. typedef struct Student Student_t;
  13.  
  14. struct StudentList
  15. {
  16.     Student_t student;
  17.     struct StudentList *next;
  18. };
  19.  
  20. typedef struct StudentList StudentList_t;
  21.  
  22.  
  23. void delete_all(StudentList_t **head)
  24. {
  25.     StudentList_t *temp;
  26.     while(*head) {
  27.         temp = *head;
  28.         *head = (*head)->next;
  29.         free(temp);
  30.     }
  31.    
  32.     *head = NULL;
  33. }
  34.  
  35. StudentList_t* read_from_binary(StudentList_t *head, FILE *fp)
  36. {
  37.     Student_t student;
  38.     StudentList_t *current;
  39.     int res;
  40.     while(1) {
  41.         res = fread(&student, 1, sizeof(Student_t), fp);
  42.         if(res < 1) {
  43.             break;
  44.         }
  45.        
  46.         if(head == NULL) {
  47.             head = malloc(sizeof(StudentList_t));
  48.             head->student = student;
  49.             current = head;
  50.         } else {
  51.             current->next = malloc(sizeof(StudentList_t));
  52.             current->next->student = student;
  53.             current = current->next;
  54.         }
  55.     }
  56.    
  57.     return head;
  58. }
  59.  
  60. double get_avg_grade(StudentList_t *head)
  61. {
  62.     double avg = 0;
  63.     int count = 0;
  64.     while(head) {
  65.         avg += head->student.avg_grade;
  66.         count += 1;
  67.         head = head->next;
  68.     }
  69.    
  70.     if(count > 0) {
  71.         avg = avg / count;
  72.     } else {
  73.         avg = 0;
  74.     }
  75.  
  76.     return avg;
  77. }
  78.  
  79. void write_to_bin_file(StudentList_t *head, char* file_name)
  80. {
  81.     FILE *fp = fopen(file_name, "wb");
  82.     if(fp == NULL) {
  83.         perror("Cannot open file");
  84.         exit(EXIT_FAILURE);
  85.     }
  86.    
  87.     while(head) {
  88.         fwrite(&head->student, 1, sizeof(Student_t), fp);
  89.         head = head->next;
  90.     }
  91.    
  92.     fclose(fp);
  93. }
  94.  
  95. void insert_student(StudentList_t **head, Student_t student)
  96. {
  97.     StudentList_t *temp;
  98.     if(*head == NULL) {
  99.         *head = malloc(sizeof(StudentList_t));
  100.         (*head)->student = student;
  101.         (*head)->next = NULL;
  102.     } else {
  103.         temp = malloc(sizeof(StudentList_t));
  104.         temp->next = *head;
  105.         *head = temp;
  106.     }
  107. }
  108.  
  109. int main () {
  110.     return 0;
  111. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement