Advertisement
hamaXD

CPT lab05-02 อันที่ถูก

Sep 24th, 2017
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.09 KB | None | 0 0
  1. //main.c
  2. #include<stdio.h>
  3. #include<string.h>
  4. #include<stdlib.h>
  5. struct employee {
  6.   char name[128];
  7.   float salary;
  8. };
  9. typedef struct employee Employee;
  10. float total_salary(Employee a[], int len);
  11. int main() {
  12.     int num,i=0,j=0;
  13.     Employee *all;
  14.     FILE *fp;
  15.     printf("Enter num: ");
  16.     scanf("%d",&num);
  17.     all=(Employee *)malloc(num*sizeof(Employee));
  18.    
  19.     printf("\nInput---------\n");
  20.     fp=fopen("employee.bin","w+");
  21.     while(i<num){ fflush(stdin);
  22.         printf("[%d]name : ",i+1);
  23.         gets((all+i)->name);
  24.         printf("[%d]salary : ",i+1);
  25.         scanf("%f",&(all+i)->salary);
  26.         fwrite(&all,sizeof(Employee),1,fp);
  27.         i++;
  28.     }
  29.     fclose(fp);
  30.    
  31.     fp=fopen("employee.bin","r+");
  32.     printf("\nRead---------\n");
  33.     fread(&all,sizeof(Employee),1,fp);
  34.     for(i=0; i<num; i++){
  35.         printf("%s:%.2f\n",(all+i)->name,(all+i)->salary);
  36.     }
  37.     fclose(fp);
  38.  
  39.     printf("\nTotal Salary = %.1f\n", total_salary(all, num));
  40.     free(all);
  41.  
  42.            
  43.     fclose(fp);
  44.     return 0;  
  45. }
  46.  
  47.  
  48.  
  49. float total_salary(Employee a[], int len){
  50.     int i;
  51.     float sum=0;
  52.     for(i=0; i<len; i++)
  53.     sum+=(a+i)->salary;
  54.     return sum;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement