📄 sunum.c
字号:
#include "stdio.h"
#include "user.h"
void SortByUserNum()
{
int i,j,k;
user TempS;
user *s,*t;
int total=SIZE;/* SIZE 在shead.h头文件中定义的常量值为100 */
int recNumber=0;
char DataFile[10]="yonghu";
FILE * fp;/* fp指针指向存储数据的文件名 */
fp=fopen(DataFile,"rb");
clrscr();
if(fp==NULL)
{
printf("\nOpen file %s fail!End with any key\n",DataFile);
perror("Open file fail");
getch();
exit(1);
}
/* printf("read data from file!\n"); */
/* 将文件中要排序的信息存入结构体数组 */
s=malloc(total*sizeof(user));
if(s==NULL)
{
printf("allot memory fail!\n");
printf("press any key to continu...\n");
fflush(stdin);
getch();
return;
}
while((fread(&TempS,sizeof(user),1,fp)!=(int)NULL))
{
s[recNumber].Number=TempS.Number;
strcpy(s[recNumber].Name,TempS.Name);
strcpy(s[recNumber].ps,TempS.ps);
s[recNumber].power=TempS.power;
recNumber++;
if(recNumber>=total)
{
total+=INCREAMENT;
t=realloc(s,total*sizeof(user));
if(t==NULL)
{
printf("allot memory fail!\n");
printf("press any key to continu...\n");
free(s);/*释放内存*/
fflush(stdin);
getch();
return;
}
s=t;
t=NULL;
}
}
fclose(fp);
/* printf("%d users",recNumber); */
/* 如果文件中有记录,则将各条记录按序号排序 */
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;
}
if(k!=i)
{
TempS.Number=s[k].Number;
strcpy(TempS.Name,s[k].Name);
strcpy(TempS.ps,s[k].ps);
TempS.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=TempS.Number;
strcpy(s[i].Name,TempS.Name);
strcpy(s[i].ps,TempS.ps);
s[i].power=TempS.power;
}
}
/* 将排序好的结构体记录写入文件 */
fp=fopen(DataFile,"wb+");
if(fp==NULL)
{
printf("\nSet up file %s fail!End with anykey.\n",DataFile);
perror("Set up fail");
free(s);/*释放内存*/
fflush(stdin);
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!");
free(s);/*释放内存*/
fflush(stdin);
getch();
exit(1);
}
}
fclose(fp);
}
else if(recNumber==0)
{
printf("\n No users!\n");
printf("press any key to continu...");
free(s);/*释放内存*/
fflush(stdin);
getch();
return;
}
/* 显示排序后的文件 */
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 %s fail!End with any key\n",DataFile);
perror("Open file fail");
free(s);/*释放内存*/
fflush(stdin);
getch();
exit(1);
}
printf("\nNumber\t\tName\t\tpassword\t\tpower\n");
while(fread(&TempS,sizeof(user),1,fp)!=(int)NULL)
{
printf("\n%ld\t\t%s\t\t%-8s\t\t%d\n",TempS.Number,TempS.Name,TempS.ps,TempS.power);
}
fclose(fp);
printf("press any key to continu...");
fflush(stdin);
getch();
free(s);/*释放内存*/
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -