1> 使用fgets统计给定文件的行数
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//定义文件指针
FILE *fp=NULL;
//打开文件(只读)
if((fp=fopen("./test.txt","r"))==NULL)
{
perror("error fopen");
return -1;
}
//定义数组
char buf[10]="";
//读取fp到buf中
int i=0;
while(1)
{
char *ptr=fgets(buf,sizeof(buf),fp);
if(ptr==NULL)
{
break;
}
for(int j=0;j<10;j++)
{
if(buf[j]=='\n')
{
i++;
}
}
}
printf("n=%d\n",i);
//关闭文件
fclose(fp);
return 0;
}
2> 使用fputs和fgets完成两个文件的拷贝
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//定义文件指针
FILE *fpr=NULL;
if((fpr=fopen("./test.txt","r"))==NULL)
{
perror("fopen error");
return -1;
}
FILE *fpw=NULL;
if((fpw=fopen("./test1.txt","w"))==NULL)
{
perror("fopen error");
return -1;
}
//定义数组
char buf[10]="";
//读取fpr到buf中
while(1)
{
char *ptr=fgets(buf,sizeof(buf),fpr);
if(ptr==NULL)
{
break;
}
fputs(buf,fpw);
}
fclose(fpr);
fclose(fpw);
return 0;
}
3> 完成注册登录功能
做个小菜单,功能1是注册功能,输入注册账户和注册密码,将账户和密码写入文件中。功能2是登录功能,提示并输入登录账户和登录密码,并用其遍历文件中的每一组账户和密码,如果匹配成功,则登录成功,如果全部不匹配则提示登录失败
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
int menu=0;
while(1)
{
system("clear");
printf("\t\t=====login interface=====\n");
printf("\t\t=====1、register=====\n");
printf("\t\t=====2、log in=====\n");
printf("\t\t=====3、exit=====\n");
printf("please enter options:");
scanf("%d",&menu);
getchar();
switch(menu)
{
case 1:
{
//注册功能
FILE *fp1=NULL;
if((fp1=fopen("./ID.c","a"))==NULL)
{
perror("fopen error");
return -1;
}
FILE *fp2=NULL;
if((fp2=fopen("./passwd.c","a"))==NULL)
{
perror("fopen error");
return -1;
}
printf("please enter your id:");
char id[4]="";
fprintf(fp1,"%s\n",id);
printf("please enter your passwd:");
char passwd[6]="";
fprintf(fp2,"%s\n",passwd);
printf("created successfully\n");
fclose(fp1);
fclose(fp2);
}
break;
case 2:
{
//登录功能
FILE *fp1=NULL;
if((fp1=fopen("./ID.c","r"))==NULL)
{
perror("fopen error");
return -1;
}
FILE *fp2=NULL;
if((fp2=fopen("./passwd.c","r"))==NULL)
{
perror("fopen error");
return -1;
}
printf("please enter your id:");
char id[4]="";
scanf("%s",id);
char buf1[4]="";
while(1)
{
fgets(buf1,sizeof(buf1),fp1);
for(int i=0;i<sizeof(buf1);i++)
{
if(id[i]==buf1[i])
{
}
}
}
char passwd[6]="";
}
break;
case 3:goto END;
default:printf("error options,please try again!\n");
}
//提示结束
printf("please enter any key to end\n");
while(getchar()!='\n');
}
END:
return 0;