1、使用这fscanf和fprintf两个函数实现文件的拷贝。
#include <myhead.h>int main(int argc, const char *argv[])
{//使用这fscanf和fprintf两个函数实现文件的拷贝FILE *fp1 = fopen("./1.txt","r"); //打开被拷贝的文件1.txtif(NULL== fp1){perror("fopen1");return -1;}FILE *fp2 = fopen("./2.txt","w"); //只写的方式打开if(NULL == fp2){perror("fopen2");return -1;}char buff[1024];while(EOF != fscanf(fp1,"%1023s",buff)) //限制打小,防止溢出{fprintf(fp2,"%s\n",buff); //保持换行一致}fclose(fp1);fclose(fp2);return 0;
}
2、fwrite和fread实现文件拷贝。
#include <myhead.h>int main(int argc, const char *argv[])
{FILE *fp1,*fp2;fp1 = fopen("./1.txt","r");if(NULL == fp1){perror("fp1");return -1;}fp2 = fopen("./2.txt","w");if(NULL == fp2){perror("fp2");return -1;}int res;char buff[1024];while(res = fread(buff,1,sizeof(buff),fp1)!=0){fwrite(buff,res,sizeof(buff),fp2);}fseek(fp1,SEEK_CUR,-1024);bzero(buff,sizeof(buff));fread(buff,sizeof(buff),1,fp1);fwrite(buff,sizeof(buff),1,fp2);fclose(fp1);fclose(fp2);return 0;
}
3、登录注册实现一遍。
#include"fun.h"
int main(int argc, const char *argv[])
{int ch;printf("argc = %d\targv[0] = %s\tagrv[1] = %s\n",argc,argv[0],argv[1]);if(argc!=2){printf("参数错误\n");return -1;}while(1){printf("\t\t\t1、注册\n");printf("\t\t\t2、登录\n");printf("\t\t\t0、退出\n");printf("请输入你的选择:");scanf("%d",&ch);getchar();//吸收回车switch(ch){case 1:regist(argv[1]);//注册函数break;case 2:login(argv[1]);//登录函数break;case 0:exit(EXIT_SUCCESS);//成功退出//exit(EXIT_FAILURE);//失败退出break;default:printf("输入有误请重新输入\n");}}return 0;
}#include"fun.h"
int regist(const char *File)
{char name[20],code[20];printf("请输入注册账户:");fgets(name,sizeof(name),stdin);//输入账户printf("请输入注册密码:");fgets(code,sizeof(code),stdin);//输入密码name[strlen(name)-1] = '\0';code[strlen(code)-1] = '\0';FILE *fp = fopen(File,"a");//追加写的方式写入文件if(fp==NULL){perror("fopen");return -1;}fprintf(fp,"%s %s ",name,code);//将账户密码写入文件fclose(fp);//关闭文件return 0;
}
int login(const char *File)
{char dname[20],dcode[20];//存储输入的账户密码char name[20],code[20];//存储读取的账户密码printf("请输入登录账户:");fgets(dname,sizeof(dname),stdin);//输入账户printf("请输入登录密码:");fgets(dcode,sizeof(dcode),stdin);//输入密码dname[strlen(dname)-1] = '\0';dcode[strlen(dcode)-1] = '\0';//循环读取文件内容与账户密码匹配FILE *fp = fopen(File,"r");//只读方式打开if(fp==NULL){perror("fopen");return -1;}int flag=0;while(1){int res = fscanf(fp,"%s %s",name,code);//读取到的账户密码if(res==EOF)//读取到文件末尾退出{break;}if(strcmp(dname,name)==0&&strcmp(dcode,code)==0){printf("登录成功!!!\n");flag=1;return 0;}}if(flag==0){printf("登录失败,请重新输入\n");}fclose(fp);//关闭文件return 0;
}#ifndef _FUN_H_
#define _FUN_H_
#include<myhead.h>
int regist(const char *);
int login(const char *);
#endif
思维导图