c语言细节中的文件归类代码

 题目:把a.txt文件中的内容,同一个地点的姓名归为一类。输出的时候按类输出。并且计算每类地址中姓名的总数。

Code:
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <string.h>  
  4. #define N 100  
  5.   
  6. typedef struct PERSOONSTRU  
  7. {  
  8.  char name[256];  
  9. }  
  10. PERSOON;  
  11. typedef struct FIERSTRU  
  12. {  
  13. int count;// 数据的总数  
  14. char add[256];// 数据的地址  
  15. PERSOON p[256];  
  16. }FIER;  
  17. int main()  
  18. {  
  19.     
  20.     FIER *data=NULL;  
  21.    char tempadd[256];  
  22.    char tempname[256];  
  23.    int m=0;  
  24.    int j=0;  
  25.    int i=0;  
  26.    FILE *pFile;  
  27.    data = (FIER*)malloc(sizeof(FIER)*N);  
  28.    memset(data, 0, sizeof(FIER)*N);  
  29.    // 在c语言中函数前面是不可以插入临时变量的  
  30.      
  31.    pFile=fopen("a.txt""rb");  
  32.    if (!pFile)  
  33.    {  
  34.      fclose(pFile);  
  35.      exit(0);  
  36.    }  
  37.       
  38.    while(!feof(pFile))  
  39.    {  
  40.         
  41.      memset(tempadd, 0, 256);  
  42.      memset(tempname, 0, 256);  
  43.      fscanf(pFile, "%s%s", tempname, tempadd);  
  44.      // 执行fscanf后data[0].count变为一个不确定的数  
  45.      // 当把前面的两个函数变为memset(tempadd,0, strlen);  
  46.      for (i=0; i<m; i++)  
  47.      {  
  48.          // 存在的类别  
  49.         if (0==strcmp(data[i].add, tempadd))  
  50.         {  
  51.               
  52.             strcpy(data[i].p[data[i].count].name, tempname);  
  53.             data[i].count++;  
  54.             break;  
  55.         }  
  56.      }  
  57.      // 新的类别  
  58.      if (i==m)  
  59.      {  
  60.         strcpy(data[m].add,tempadd);  
  61.         strcpy(data[i].p[data[m].count].name, tempname);  
  62.         data[m].count++;  
  63.          m++;  
  64.      }  
  65.   
  66.    }  
  67.    for (i=0;i<m; i++)  
  68.    {  
  69.      // 输出种数  
  70.        printf("%d/n", data[i].count);  
  71.        printf(data[i].add);  
  72.        printf("/n");  
  73.        for (j=0; j<data[i].count; j++)  
  74.        {  
  75.            printf("%s/n", data[i].p[j].name);  
  76.        }  
  77.        printf("/n");  
  78.   
  79.    }  
  80.    free(data);  
  81.      
  82.    system("pause");  
  83.     return 0;  
  84. }  

文件中内容为:姓名 地点

结果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章