1> 使用fgets统计给定文件的行数
#include<myhead.h>
int main(int argc, const char *argv[])
{if(argc!=2){printf("enter error\n");return -1;}FILE*fp=NULL;if((fp=fopen(argv[1],"r"))==NULL){perror("fopen error");return -1;}int num=0;char*ch=NULL;char buf[5]="";while(1){ch=fgets(buf,sizeof(buf),fp);if(ch==NULL)break;//if(strlen(buf)<4)if(buf[strlen(buf)-1]=='\n')num++;}printf("num=%d\n",num);fclose(fp);return 0;
}
2> 使用fputs和fgets完成两个文件的拷贝
#include<myhead.h>
int main(int argc, const char *argv[])
{if(argc!=3){printf("enter error\n");return -1;}FILE*fp1=NULL;if((fp1=fopen(argv[1],"r"))==NULL){perror("fopen error");return -1;}FILE*fp2=NULL;if((fp2=fopen(argv[2],"w"))==NULL){perror("fopen error");return -1;}char*ch=NULL;char buf[5]="";while(1){ch=fgets(buf,sizeof(buf),fp1);if(ch==NULL)break;fputs(buf,fp2);}puts("拷贝成功");fclose(fp1);fclose(fp2);return 0;
}
3> 完成注册登录功能
做个小菜单,功能1是注册功能,输入注册账户和注册密码,将账户和密码写入文件中
功能2是登录功能,提示并输入登录账户和登录密码,并用其遍历文件中的每一组账户和密码,如果匹配成功,则登录成功,如果全部不匹配则提示登录失败
#include<myhead.h>
void do_login()
{char id[20],password[20];puts("请输入你要登录的账号");fgets(id,sizeof(id),stdin);puts("请输入你要登录的密码");fgets(password,sizeof(password),stdin);id[strlen(id)-1]='\0';password[strlen(password)-1]='\0';FILE*fp=NULL;if((fp=fopen("id.txt","r"))==NULL){perror("fopen error");return;}char*ch=NULL;char buf[20],rbuf[20];while(1){int rew=fscanf(fp,"%s %s",buf,rbuf);if(rew<=0){puts("账号未注册or账号密码不正确");break;}if(strcmp(id,buf)==0 && strcmp(password,rbuf)==0){puts("登录成功");break;}}fclose(fp);}
void do_register()
{char id[20],password[20];puts("请输入你要注册的账号");fgets(id,sizeof(id),stdin);puts("请输入你要注册的密码");fgets(password,sizeof(password),stdin);id[strlen(id)-1]='\0';password[strlen(password)-1]='\0';FILE*fp=NULL;if((fp=fopen("id.txt","a+"))==NULL){perror("fopen error");return;}int rew=fprintf(fp,"%s %s\n",id,password);if(rew<0){puts("注册失败");}else{puts("注册成功");}fclose(fp);
}
int main(int argc, const char *argv[])
{while(1){system("clear");printf("\t\t************登录界面***********\n");printf("\t\t************1、登录***********\n");printf("\t\t************2、注册***********\n");printf("\t\t************3、退出***********\n");int n;printf("请输入你要选择的功能\n");scanf("%d",&n);getchar();switch(n){case 1:do_login();break;case 2:do_register();break;case 3:exit(EXIT_SUCCESS);break;default:puts("您输入的功能有误,请重新输入");}puts("输入任意键当回车结束");while(getchar()!='\n');}return 0;
}