📄 bintro.c
字号:
#ifndef BROWSEINTRO
#define BROWSEINTRO
#include "stdio.h"
#include "shead.h"
#include "malloc.h"
void BrowseIntro()
{
int i,j,k;
candidate TempS;
int total=CANDIDATENUM;/*存放的是当前s的大小*/
candidate *t=NULL,*s=NULL;
int recNumber=0;
char DataFile[10]="houshuan";
FILE * fp=NULL;
s=(candidate *)malloc(sizeof(candidate)*CANDIDATENUM);/* houshuan 在shead.h头文件中定义的常量值为20 */
if(s==NULL)
{
printf("allot memory fail!");
printf("press any key to continu...");
getch();
return;
}
fp=fopen(DataFile,"rb");
clrscr();
if(fp==NULL)
{
printf("\nfp=%ld\n",fp);
printf("\nOpen file %s fail!End with any key\n",DataFile);
perror("Open file fail");
getch();
free(s);/*释放内存*/
exit(1);
}
/* 将文件中要排序的信息存入结构体数组 */
while((fread(&TempS,sizeof(candidate),1,fp)!=(int)NULL))
{
s[recNumber].Number=TempS.Number;
strcpy(s[recNumber].Name,TempS.Name);
strcpy(s[recNumber].intro,TempS.intro);
s[recNumber].votenum=TempS.votenum;
recNumber++;
if(recNumber>=total)/*当s被用完时重新分配大小*/
{
total+=INCREASE;/*INCREAT在shead头文件中定义*/
t=(candidate *)realloc(s,sizeof(candidate)*total);
if(t==NULL)
{
printf("allot memory fail!");
printf("press any key to continu...");
free(s);
fflush(stdin);
getch();
return;
}
s=t;
t=NULL;
}
}
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;
}
if(k!=i)
{
TempS.Number=s[k].Number;
strcpy(TempS.Name,s[k].Name);
strcpy(TempS.intro,s[k].intro);
TempS.votenum=s[k].votenum;
s[k].Number=s[i].Number;
strcpy(s[k].Name,s[i].Name);
strcpy(s[k].intro,s[i].intro);
s[k].votenum=s[i].votenum;
s[i].Number=TempS.Number;
strcpy(s[i].Name,TempS.Name);
strcpy(s[i].intro,TempS.intro);
s[i].votenum=TempS.votenum;
}
}
/* 将排序好的结构体记录写入文件 */
fp=fopen(DataFile,"wb+");
if(fp==NULL)
{
printf("\nSet up file %s fail!End with anykey.\n",DataFile);
perror("Set up fail");
getch();
free(s);/*释放内存*/
exit(1);
}
for(i=0;i<recNumber;i++)
{
if(fwrite(&s[i],sizeof(candidate),1,fp)!=1)
{
printf("\nwrite file %s fail!End with anykey.\n",DataFile);
perror("Write file fail!");
getch();
free(s);/*释放内存*/
exit(1);
}
}
fclose(fp);
}
else if(recNumber<1)
{
printf("\nNo cnadidate\n");
printf("press any key to continu...");
getch();
free(s);/*释放内存*/
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");
getch();
free(s);/*释放内存*/
exit(1);
}
while(fread(&TempS,sizeof(candidate),1,fp)!=(int)NULL)
{
printf("\nNumber:%ld\tName:%s\nintro:%s\nvote:%d\n\n",TempS.Number,TempS.Name,TempS.intro,TempS.votenum);
printf("press any key to next...\n");
fflush(stdin);
getch();
}
fclose(fp);
free(s);/*释放内存*/
}
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -