sunum.c
上传用户:tamljx
上传日期:2021-06-04
资源大小:60k
文件大小:3k
- /* sunum.c按家庭成员序号排序浏览用户信息 */
- #include "stdio.h"
- void SortByUserNum()
- {
- int i,j,k;
- user TmpS;
- user s[SIZE];/*SIZE,在shead.h头文件中定义的常量,值为100 */
- int recNumber = 0;
- char DataFile[40] = "yonghu";
- FILE *fp;/*====fp指针指向存储数据的文件名====*/
- fp=fopen(DataFile,"rb");
- if (fp == NULL)
- {
- printf("nOpen file %s fail!End with any keyn",DataFile);
- perror("Open file fail");
- getch();
- exit(1);
- }
- /*将文件中要排序的信息存入结构体数组*/
- while((fread(&TmpS,sizeof(user),1,fp)) != (int)NULL)
- {
- s[recNumber].Number = TmpS.Number;
- strcpy(s[recNumber].Name, TmpS.Name);
- strcpy(s[recNumber].ps,TmpS.ps);
- s[recNumber].power = TmpS.power;
- recNumber++;
- }
- fclose(fp);
- /*====如果文件中有记录,则将各条记录按序号排序===*/
- if(recNumber>1)
- {
- /*====用选择排序法进行按序号的排序====*/
- for(i=0;i<recNumber-1;i++)
- {
- k = i;
- for(j=i+1;j<recNumber;j++)
- {
- if(s[k].Number<s[j].Number) k = j;
- }
- TmpS.Number = s[k].Number;
- strcpy(TmpS.Name,s[k].Name);
- strcpy(TmpS.ps,s[k].ps);
- TmpS.power = s[k].power;
- s[k].Number = s[i].Number;
- strcpy(s[k].Name,s[i].Name);
- strcpy(s[k].ps,s[i].ps);
- s[k].power = s[i].power;
- s[i].Number = TmpS.Number;
- strcpy(s[i].Name,TmpS.Name);
- strcpy(s[i].ps,TmpS.ps);
- s[i].power = TmpS.power;
- }
- /*====将排序好的结构体记录写入文件====*/
- fp=fopen(DataFile,"wb+");
- if (fp == NULL)
- {
- printf("nSet up file %sfail !end with anykey.n",DataFile);
- perror("Set up fail");
- getch();
- exit(1);
- }
- for(i=0; i<recNumber; i++)
- {
- if(fwrite(&s[i],sizeof(user),1,fp)!=1)
- {
- printf("nWrite file %s fail!end with anykey.n",DataFile);
- perror("Write file fail!");
- getch();
- exit(1);
- }
- }
- fclose(fp);
- }
- /*====显示排序后的文件====*/
- printf("The content in the user file is:.n",DataFile);
- printf("Content as follow:n");
- fp=fopen(DataFile,"rb");
- if (fp == NULL)
- {
- printf("nOpen file%sfail!End with any key n",DataFile);
- perror("Open file fail");
- getch();
- exit(1);
- }
- printf("nNumbertNametpstpowern");
- while(fread(&TmpS,sizeof(user),1,fp) != (int)NULL)
- {
- printf("n%ldt%st%st%dn",TmpS.Number,TmpS.Name,TmpS.ps,TmpS.power);
- }
- fclose(fp);
- }