📄 tovote.c
字号:
#ifndef VOTE
#define VOTE
#include "stdio.h"
#include "shead.h"
void vote()
{
int i,j,k,flag;/*flag用来标志是否找对应编号,即投票是否成功*/
long candidatenum;/* 定义进行操作时的临时结构体变量 */
long Number; /* */
candidate TempS;
candidate *s,*t;
int total=CANDIDATENUM;/* CANDIDATENUM在头文件中定义,为10 */
int recNumber;
char DataFile[10]="houshuan",next;
/* DataFile存储候选人信息的文件名,next为是否进行下一次投标操作的选项 */
FILE * fp;
s=(candidate*)malloc(total*sizeof(candidate));
if(s==NULL)
{
printf("allot memory fail!\n");
printf("press any key to continu...");
fflush(stdin);
getch();
return;
}
clrscr();
begin:
flag=0;
fp=fopen(DataFile,"rb");
if(fp==NULL)
{
printf("\nOpen file %s fail !End with any key\n",DataFile);
perror("OPen file fail");
free(s);/*释放内存*/
getch();
exit(1);
}
printf("Please input the candidate's deatnum whitch you will vote:");
scanf("%ld",&candidatenum);
printf("The candidate you will vote is:%ld\n",candidatenum);
Number=candidatenum;
/* 将文件中要修改的信息存入结构数组 */
recNumber=0;
/*将文件中的数据读入结构体数组,如果文件中的数候选人号和要投票的候选人号不符,则原样写入
如果文件中数据的候选人号和要投票候选人号不符,则原样写入数组,如文件中数据的候选人号和
要投票候选人号匹配,则根据其他信息如序号、姓名、简介等仍原样写入数组,但票数加一后写入数组即修改 */
while((fread(&TempS,sizeof(candidate),1,fp))!=(int)NULL)
{
if(TempS.Number!=candidatenum)
{
s[recNumber].Number=TempS.Number;
strcpy(s[recNumber].Name,TempS.Name);
strcpy(s[recNumber].intro,TempS.intro);
s[recNumber].votenum=TempS.votenum;
}
else
{
s[recNumber].Number=Number;
strcpy(s[recNumber].Name,TempS.Name);
strcpy(s[recNumber].intro,TempS.intro);
s[recNumber].votenum=TempS.votenum+1;
flag=1;
/* 用户不可以修改候选人姓名、简介,所以仍为文件中原值,但票数加一 */
}
recNumber++;
if(total<=recNumber)
{
total+=INCREASE;
t=realloc(s,total*sizeof(candidate));
if(t==NULL)
{
printf("allot memory fail!\n");
printf("press any key to continu...");
free(s);/*释放内存*/
getch();
return;
}
s=t;
t=NULL;
}
}
fclose(fp);
if(flag==0)
{
printf("vote fail!the number not find!\n");
printf("press any key to continu...\n");
getch();
return;
}
else
{
printf("vote success!\n");
}
/* 将修改后的结构体数组记录写入文件 */
fp=fopen(DataFile,"wb");
if(fp==NULL)
{
printf("\nSet up file %s fail !End with any key.\n",DataFile);
perror("Set up fail");
free(s);/*释放内存*/
getch();
exit(1);
}
for(i=0;i<recNumber;i++)
{
if(fwrite(&s[i],sizeof(candidate),1,fp)!=1)
{
printf("\nWrite file %s fail!end with any key.\n",DataFile);
perror("Write file fail!");
free(s);/*释放内存*/
getch();
exit(1);
}
}
fclose(fp);
/* 显示投票后的投票情况 */
fp=fopen(DataFile,"rb");
if(fp==NULL)
{
printf("\nOpen file %s fail!End with any key\n",DataFile);
perror("Open file fail");
free(s);/*释放内存*/
getch();
exit(1);
}
printf("the file after modify is:\n");
printf("\nNumber \tName\tvotenum\n");
while(fread(&TempS,sizeof(candidate),1,fp)!=(int)NULL)
{
if(TempS.Number!=0)
printf("\n%ld\t%s\t%d\n",TempS.Number,TempS.Name,TempS.votenum);
}
fclose(fp);
printf("\nGo On?(y/n)");
fflush(stdin);
next=getchar();
putchar('\n');
if(next=='y'||next=='Y')goto begin;
free(s);/*释放内存*/
}
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -