1.完成注册登录功能:
做个小菜单,功能1:是注册功能,输入注册账户和注册密码,将账户和密码写入文件中
功能2:是登录功能,提示并输入登录账户和登录密码,并用其遍历文件中的每一组账户和密码,如果匹配成功,则登录成功,如果全部不匹配则提示登录失败
#include <myhead.h>
int main(int argc, const char *argv[])
{
int menu=0;
while(1)
{
system("clear");
printf("\t\t*************XXXX登录界面*****************\n");
printf("\t\t**************1.注册****************\n");
printf("\t\t**************2.登录****************\n");
printf("\t\t**************0.退出****************\n");
printf("请输入操作选项:");
scanf("%d",&menu);
getchar();
switch(menu)
{
case 1:
{
//注册
FILE *fp=NULL;
if((fp=fopen("meun.txt","a"))==NULL)
{
perror("fopen");
return -1;
}
char account[128]="";
char passwd[128]="";
printf("请输入账号:");
fscanf(stdin,"%s",account);
printf("请输入密码:");
fscanf(stdin,"%s",passwd);
fputs(account,fp);
fputs(passwd,fp);
fputc('\n',fp);
fclose(fp);
}
break;
case 2:
{
//登录
char buf[128]="";
char account[128]="";
char passwd[128]="";
FILE *fp=NULL;
if((fp=fopen("meun.txt","r"))==NULL)
{
perror("fopen");
return -1;
}
printf("请输入账号:");
fscanf(stdin,"%s",account);
strcat(buf,account);
printf("请输入密码:");
fscanf(stdin,"%s",passwd);
strcat(buf,passwd);
strcat(buf,"\n");
char rbuf[128];
printf("buf=%s\n",buf);
while(1)
{
//遍历文件中的账号和密码,如果一致,表示登录成功
char *ptr=fgets(rbuf,sizeof(rbuf),fp);
if(strcmp(rbuf,buf)==0)
{
printf("登录成功\n");
//登录成功的页面
break;
}
if(ptr==NULL)
{
printf("登录失败\n");
break;
}
}
fclose(fp);
}
break;
case 0:
{
goto END;
}
default:printf("你输入的选项有误,请重新输入\n");
//输入任意键按回车确认
printf("输入任意键按回车确认\n");
while(getchar()!='\n');
}
}
END:
return 0;
}
运行结果:
============================
2.使用fgets统计给定文件的行数
#include <myhead.h>
int main(int argc, const char *argv[])
{
FILE *fp=NULL;
if((fp=fopen(argv[1],"r"))==NULL)
{
perror("fopen error");
return -1;
}
char buf[128]="";
int line=0;
while(1)
{
char *ptr=fgets(buf,sizeof(buf),fp);
if(buf[strlen(buf)-1]=='\n')
line++;
if(ptr==NULL)
break;
}
printf("line=%d\n",line);
fclose(fp);
return 0;
}
运行结果:
3.使用fputs和fgets完成两个文件的拷贝
#include <myhead.h>
int main(int argc, const char *argv[])
{
if(argc!=3)
{
printf("input file error\n");
printf("usage:./a.out srcfile destfile\n");
return -1;
}
FILE *fp=NULL;
FILE *fp1=NULL;
if((fp=fopen(argv[1],"r"))==NULL)
{
perror("fopen error");
return -1;
}
if((fp1=fopen(argv[2],"w"))==NULL)
{
perror("fopen error");
return -1;
}
char buf[128]="";
while(1)
{
char *ptr=fgets(buf,sizeof(buf),fp);
if(ptr==NULL)
break;
fputs(buf,fp1);
}
fclose(fp);
fclose(fp1);
return 0;
}
运行结果: