将学生结构体写入文件
1 #include <stdio.h> 2 #include <string.h> 3 struct Student 4 { 5 char m_name[20]; //姓名 6 int m_age; //年龄 7 int m_height; //身高 8 }; 9 typedef struct Student Student_t; 10 11 void Student_Print(const Student_t *v,int len) 12 { 13 for(int i = 0; i < len ; i++) 14 { 15 printf("姓名:%s\t年龄:%d\t身高:%d\n",v[i].m_name,v[i].m_age,v[i].m_height); 16 } 17 printf("--------------------------\n"); 18 } 19 20 void sort(Student_t *v,int len,int (*cmp)(void *,void *)) 21 { 22 Student_t temp; 23 for(int i = 0; i < len ;i++) 24 { 25 for(int j = 0; j < len - 1;j++) 26 { 27 if(cmp(&v[j],&v[j+1]) > 0) 28 { 29 //swap 30 temp = v[j]; 31 v[j] = v[j+1]; 32 v[j+1] = temp; 33 } 34 } 35 } 36 } 37 38 int Student_age(void *data_1,void *data_2) 39 { 40 Student_t *num_1 = data_1; 41 Student_t *num_2 = data_2; 42 43 return num_1->m_age - num_2->m_age; 44 } 45 46 47 int Student_name(void *data_1,void *data_2) 48 { 49 Student_t *num_1 = data_1; 50 Student_t *num_2 = data_2; 51 52 return strcmp(num_1->m_name,num_2->m_name); 53 } 54 55 int Student_height(void *data_1,void *data_2) 56 { 57 Student_t *num_1 = data_1; 58 Student_t *num_2 = data_2; 59 60 return num_1->m_height - num_2->m_height; 61 } 62 63 int Student_age_height(void *data_1,void *data_2) 64 { 65 Student_t *num_1 = data_1; 66 Student_t *num_2 = data_2; 67 if(num_1->m_age - num_2->m_age == 0) 68 { 69 return num_1->m_height - num_2->m_height; 70 } 71 72 return num_1->m_age - num_2->m_age; 73 } 74 75 int main() 76 { 77 #if 0 78 Student_t stu[] = {{"张三",18,165},{"李四",20,170},{"王五",17,155},{"周六",19,190},{"磊磊",20,180},{"麻子",17,180},{"马云",18,160}}; 79 #else 80 Student_t stu[7]; 81 memset(stu,0,sizeof(stu)); //清空操作 82 #endif 83 int len = sizeof(stu) / sizeof(stu[0]); 84 Student_Print(stu,len); 85 //sort(stu,len,Student_age); //年龄的升序 86 //sort(stu,len,Student_name); //姓名的升序 87 //sort(stu,len,Student_height); //身高的升序 88 FILE *fp = NULL; 89 fp = fopen("Student.txt","r+"); 90 if(fp == NULL) 91 { 92 printf("打开文件失败:\n"); 93 return -1; 94 } 95 #if 0 96 sort(stu,len,Student_age_height); //先排年龄后排身高 97 for(int i = 0 ; i < len;i++) 98 { 99 fprintf(fp,"%s %d %d\n",stu[i].m_name,stu[i].m_age,stu[i].m_height); 100 } 101 #else 102 for(int i = 0 ; i < len;i++) 103 { 104 fscanf(fp,"%s %d %d\n",stu[i].m_name,&stu[i].m_age,&stu[i].m_height); 105 } 106 #endif 107 Student_Print(stu,len); 108 109 fclose(fp); 110 111 return 0; 112 }