1.使用分文件编译,实现注册登录界面,使用fgets,fscanf,fpritnf函数。
主函数
#include "log.h"
int main(int argc, const char *argv[])
{
int key;
while(1)
{
printf("**********1.注册**********\n");
printf("**********2.登录**********\n");
printf("**********3.退出**********\n");
printf("\n请输入要执行的步骤:");
scanf("%d",&key);
getchar();
switch(key)
{
case 1:regist();break;
case 2:login();break;
case 3:exit(EXIT_SUCCESS);break;
}
}
return 0;
}
注册函数
#include"log.h"
int regist()
{
user reg;
printf("请输入注册账户:");
fgets(reg.name,sizeof(reg.name),stdin);
printf("请输入注册账户的密码:");
fgets(reg.code,sizeof(reg.code),stdin);
FILE *fp = fopen("./user.txt","w");
if(fp==NULL)
{
perror("fopen");
return -1;
}
fprintf(fp,"%s%s",reg.name,reg.code);
printf("注册成功\n");
fclose(fp);
return 0;
}
登录函数:
#include"log.h"
int login()
{
user reg,log;
printf("请输入登录账户:");
fgets(log.name,sizeof(log.name),stdin);
printf("请输入登录密码:");
fgets(log.code,sizeof(log.code),stdin);
FILE *fp = fopen("./user.txt","r");
if(fp==NULL)
{
perror("fopen");
return -1;
}
fscanf(fp,"%s%s",reg.name,reg.code);
reg.name[strlen(reg.name)+1]='\0';
reg.name[strlen(reg.name)]='\n';
reg.code[strlen(reg.code)]='\n';
reg.code[strlen(reg.code)+1]='\0';
printf("%s%s",reg.name,reg.code);
if(strcmp(log.name,reg.name)==0&&
strcmp(log.code,reg.code)==0)
{
printf("登录成功\n");
}
else
{
printf("登录失败,密码或账户名错误\n");
}
return 0;
}
另一种写法:
int remove_line(char *str)
{
int len = strlen(str);
if(len>0 && str[len-1] =='\n')
{
str[len-1] ='\0';
}
}
int login()
{
user reg,log;
printf("请输入登录账户:");
fgets(log.name,sizeof(log.name),stdin);
remove_line(log.name);
printf("请输入登录密码:");
fgets(log.code,sizeof(log.code),stdin);
remove_line(log.code);
FILE *fp = fopen("./user.txt","r");
if(fp==NULL)
{
perror("fopen");
return -1;
}
fscanf(fp,"%s%s",reg.name,reg.code);
printf("%s%s",reg.name,reg.code);
if(strcmp(log.name,reg.name)==0&&
strcmp(log.code,reg.code)==0)
{
printf("登录成功\n");
}
else
{
printf("登录失败,密码或账户名错误\n");
}
return 0;
}
头文件:定义存储账户和密码的结构体
#ifndef __LOG_H__
#define __LOG_H__
#include<myhead.h>
typedef struct
{
char name[50];
char code[50];
}user;
int login();
int regist();
#endif
2.使用fread和fwrite拷贝文件。
#include <myhead.h>
int main(int argc, const char *argv[])
{
char arr[1024];
FILE *fp1 = fopen("./1.txt","r");//只读方式打开文件1
if(NULL==fp1)
{
perror("fp1");
return -1;
}
fread(arr,sizeof(arr),1,fp1);
FILE *fp2 = fopen("./2.txt","w");//只写清空方式打开文件2
if(NULL==fp2)
{
perror("fp2");
return -1;
}
fwrite(arr,sizeof(arr),1,fp2);
fclose(fp1);
fclose(fp2);
char arr1[1024];
fp2 = fopen("./2.txt","r");//只读方式打开文件2
if(NULL==fp2)
{
perror("fp2");
return -1;
}
fread(arr1,1,sizeof(arr1),fp2);
printf("%s\n",arr1);
fclose(fp2);
return 0;
}
标签:code,name,fscanf,int,fwrite,fread,printf,reg,log
From: https://blog.csdn.net/m0_58572142/article/details/141401453