1、给定任意文件计算行数
#include<stdio.h>
#include<string.h>
#include<stdlib.h>int main(int argc, char const *argv[])
{//判断终端输入的文件if(argc!=2){puts("input file error");puts("usage:./a.out filename");return -1;}//以只读方式打开文件FILE *fp=NULL;int line=0;if((fp=fopen(argv[1],"r"))==NULL){perror("fopen error");return -1;}char buf[10];while(1){fgets(buf,sizeof(buf),fp);for(int i=0;i<strlen(buf);i++){if(buf[i]=='\n')line++;}if(strlen(buf)==0)break;memset(buf,0,sizeof(buf));}printf("line=%d\n",line);//关闭文件fclose(fp);return 0;
}
2、使用fgetc、fputc完成两个文件的拷贝
#include<stdio.h>
#include<string.h>
#include<stdlib.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 *srcfp=NULL;FILE *destfp=NULL;//以只读的方式打开源文件if((srcfp=fopen(argv[1],"r"))==NULL){perror("fopen error");return -1;}//以只写的方式打开目标文件if((destfp=fopen(argv[2],"w"))==NULL){perror("fopen error");return -1;}char buf[10]="";while(1){//将源文件拷贝到目标文件中fgets(buf,sizeof(buf),srcfp);fputs(buf,destfp);if(strlen(buf)==0)break;memset(buf,0,sizeof(buf));}printf("copy success!\n");return 0;
}
3、完成注册登录功能
做个小菜单,功能1是注册功能,输入注册账户和注册密码,将账户和密码写入文件中
功能2是登录功能,提示并输入登录账户和登录密码,并用其遍历文件中的每一组账户和密码,如果匹配成功,则登录成功,如果全部不匹配则提示登录失败
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(int argc, const char *argv[])
{int menu = 0;while(1){//system("clear"); //执行终端指令printf("\t\t======XXX登录界面============\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;char buf[20]="";if((fp=fopen("./id.txt","a"))==NULL){perror("fopen error");return -1;}printf("please enter the id:");fgets(buf,sizeof(buf),stdin);fputs(buf,fp);memset(buf,0,sizeof(buf));}break;case 2:{//登录功能char buf1[20]="";printf("please enter the id:");fgets(buf1,sizeof(buf1),stdin);FILE *fp=NULL;if((fp=fopen("./id.txt","r"))==NULL){perror("fopen error");return -1;}char buf2[20]="";while(1){if(fgets(buf2,sizeof(buf2),fp)==NULL)break;if(strcmp(buf1,buf2)==0){printf("success!\n");return 0;}memset(buf2,0,sizeof(buf2));}}break;case 0:goto END;default:printf("您输入的功能有误,请重新输入\n");}//提示输入任意键按回车结束printf("请输入任意键按回车结束!!!\n");while(getchar() != '\n');}END:return 0;
}