Advertisement
hamaXD

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

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