1.使用fgets统计给定文件的行数
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{FILE *fp=NULL;if((fp=fopen("./test1.txt","r"))==NULL){perror("错误信息");return -1;}int count=0;char str[100];while(fgets(str,sizeof(str),fp)!=NULL);{for(int i=0;i<strlen(str);i++){if(str[strlen(str)-1]=='\n'){count++;}}}printf("%d\n",count);fclose(fp);return 0;
}
2> 使用fputs和fgets完成两个文件的拷贝
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{FILE *fp1=NULL;FILE *fp2=NULL;if((fp1=fopen("./test.txt","w"))==NULL){perror("error");return -1;}if((fp2=fopen("./test1.txt","r"))==NULL){perror("error");return -1; }char str[5]="";while(fgets(str,sizeof(str),fp2)!=NULL){fputs(str,fp1);}fclose(fp1);fclose(fp2);return 0;
}
3> 完成注册登录功能
做个小菜单,功能1是注册功能,输入注册账户和注册密码,将账户和密码写入文件中
功能2是登录功能,提示并输入登录账户和登录密码,并用其遍历文件中的每一组账户和密码,如果匹配成功,则登录成功,如果全部不匹配则提示登录失败
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{FILE *fp1=NULL;FILE *fp2=NULL;char zh[100]="";char ma[100]="";while(1){printf("\t\t******************登录系统****************\n");printf("\t\t*******************1.注册****************\n");printf("\t\t*******************2.登录****************\n");printf("\t\t*******************3.退出****************\n");int num;printf("输入选项:");scanf("%d",&num);switch (num){case 1:{if((fp1=fopen("./zhanghao.txt","a+"))==NULL){perror("错误信息");return -1;}if((fp2=fopen("./mima.txt","a+"))==NULL){perror("错误信息");return -1;}printf("请输入账号:");scanf("%s",zh);fprintf(fp1,"%s\n",zh);printf("请输入密码:"); scanf("%s",ma);fprintf(fp2,"%s\n",ma);fclose(fp1);fclose(fp2);break;}case 2:{if((fp1=fopen("./zhanghao.txt","r"))==NULL){perror("错误信息");return -1;}char zhku[100]="";printf("请输入账号:");scanf("%s",zhku);while(fgets(zh,sizeof(zhku),fp1)!=NULL){zh[strlen(zh)-1]='\0';if(strcmp(zh,zhku)!=0){printf("账号输入错误\n");break;}if(strcmp(zh,zhku)==0){break;}}{if((fp2=fopen("./mima.txt","r"))==NULL){perror("错误信息");return -1;}char maku[100]="";printf("请输入密码:");scanf("%s",maku);while(fgets(ma,sizeof(maku),fp2)!=NULL){ ma[strlen(ma)-1]='\0';if(strcmp(ma,maku)!=0){printf("密码错误\n");continue;}else{printf("登陆成功\n");fclose(fp1);fclose(fp2);break;}}break;}}case 3:goto END;default:printf("输入选项错误\n");}printf("输入任意键按回车结束!\n");while(getchar()!='\n');}END:return 0;
}