首页 > 代码库 > 排序好后写入文件

排序好后写入文件

  1 #include <stdio.h>  2 #include <string.h>  3 #include <stdlib.h>  4   5 struct person{  6         char *number;  7         char *name;  8         int score;  9 }; 10  11 int main() 12 { 13         struct person arr[5]; 14         FILE *fp = fopen("src", "r"); 15         FILE *fp1 = fopen("dest", "a+"); 16         if(NULL == fp) 17         { 18                 perror("fopen"); 19                 return 1; 20         } 21         char *line = NULL; 22         int len = 0, i = 0, j = 0; 23         char pn[5][50] = {0}; 24  25         while ((getline(&line, &len, fp)) != -1) 26         { 27                 j = 0; 28                 while(*line != \n){ 29                                 *(*(pn+i)+j) = *line++; 30                                 j++; 31                 } 32                 i++; 33         } 34  35         char *str; 36         int m = i; 37         char *brr[3]; 38         char *tmp; 39         for(i=0; i<m; i++) 40         { 41                 tmp = *(pn+i); 42                 for(j=0; j<3; j++){ 43                         str = strstr(tmp, "\t"); 44                         *(brr+j) = strtok(tmp, "\t"); 45                         tmp = str + 1; 46                 } 47                 arr[i].number = *(brr+0); 48                 arr[i].name = *(brr+1); 49                 arr[i].score = atoi(*(brr+2)); 50                 printf("%s %s %d\n", arr[i].number, arr[i].name, arr[i].score); 51         } 52  53         struct person ttmp; 54         for(i=0; i<m; i++) 55         { 56                 for(j=i; j<m; j++) 57                 { 58                         if(arr[i].score < arr[j].score) 59                         { 60                                 ttmp = arr[i]; 61                                 arr[i] = arr[j]; 62                                 arr[j] = ttmp; 63                         } 64                 } 65         } 66  67         char show[20]; 68         for(i=0;i<m;i++){ 69                 fputs(arr[i].number,fp1);       fputs("\t",fp1); 70                 fputs(arr[i].name,fp1);         fputs("\t",fp1); 71                 sprintf(show,"%d",arr[i].score); 72                 fputs(show,fp1);                fputs("\n",fp1); 73         } 74  75         fclose(fp); 76         fclose(fp1); 77 }

 

排序好后写入文件