目录
一.运行效果
二.完整代码
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
//定义一个字符数组结构体
typedef struct node
{
//账号
char accounts[20];
//密码
char password[20];
}node; //这里struct user相当于给结构体起别名叫 node
//函数声明
void user_login(void);
void registered(void);
int main(void)
{
//定义局部变量
char data;
//用户提示信息
printf("===================功能===================\n");
printf("a:登录\n");
printf("b:注册\n");
printf("c:退出\n");
printf("===================功能===================\n");
while (1)
{
//用户输入
printf("请选择:");
scanf("%c",&data);
switch (data)
{
case 'a':
//调用登录函数
user_login();
break;
case 'b':
registered();
break;
case 'c':
printf("退出程序成功!\n");
return 0;
default:
printf("输入格式错误,请重新输入!\n");
break;
}
//清空缓存区的空格
while (getchar()!='\n');
}
return 0;
}
//用户注册
void registered(void)
{
int ret=0;
FILE *fd;
node *new;
//打开user.txt文件
fd = fopen("user.txt", "w");
//如果打开失败则提示
if(fd == NULL)
{
printf("文件打开失败!\n");
}
//用户输入相应数据
printf("请输入用户账户名:");
scanf("%s",new->accounts);
printf("请输入用户密码:");
scanf("%s",new->password);
//把结构体写入文件user.txt
ret=fwrite(new,sizeof(node),1,fd); //账户
if(ret==0)
{
printf("注册失败\n");
}
//最后要记得关闭文件,养成习惯
fclose(fd);
}
//用户登录
void user_login(void)
{
//定义需要用的局部变量
int ret=0;
node *read_buf, user_accounts, user_password;
FILE *fd;
//打开文件user.txt
fd = fopen("user.txt","a+");
if(fd == NULL)
{
printf("文件打开失败!\n");
}
//将光标移到到开头,利于读取文件数据
fseek(fd,0,SEEK_SET);
//从文件读取到账号密码
ret=fread(read_buf,sizeof(node),1,fd);
if(ret==0)
{
printf("文件数据丢失,登录失败!\n");
return ;
}
//用户输入登录信息
printf("请输入用户账户名:");
scanf("%s",user_accounts.accounts);
printf("请输入用户密码:");
scanf("%s",user_password.password);
//判断如果用户输入的账号和密码和文件读取的一样就告诉用户登录成功
if (strcmp(user_accounts.accounts,read_buf->accounts)==0 && strcmp(user_password.password,read_buf->password)==0)
{
printf("登录成功\n");
return ;
}
//老样子,记得打开一个文件用完之后一定要关闭
fclose(fd);
}