log_regist.c
#include"log.h"
int regist() {
FILE *fp = fopen("./1.txt", "w");
if (fp == NULL) {
perror("fp");
return -1;
}
user u;
printf("输入账户: ");
fgets(u.user, sizeof(u.user), stdin);
printf("输入密码: ");
fgets(u.code, sizeof(u.code), stdin);
// 将用户信息写入文件
fprintf(fp, "%s%s", u.user, u.code);
printf("创建成功\n");
fclose(fp);
return 0;
}
int login() {
user u, l;
FILE *fp = fopen("./1.txt", "r");
if (fp == NULL) {
perror("fp");
return -1;
}
printf("输入账户: ");
fgets(l.user, sizeof(l.user), stdin);
printf("输入密码: ");
fgets(l.code, sizeof(l.code), stdin);
//fgets 会自动加\n,所以把登录的和pscanf处理后保持一致
/* if (l.user[strlen(l.user) - 1] == '\n') {
l.user[strlen(l.user) - 1] = '\0';
}
if (l.code[strlen(l.code) - 1] == '\n') {
l.code[strlen(l.code) - 1] = '\0';
}*/
//fscanf 不保留\n
while (fscanf(fp, "%s %s", u.user, u.code) != EOF) {
// 手动添加\n到用户名和密码末尾
strcat(u.user, "\n");
strcat(u.code, "\n");
if (strcmp(u.user, l.user) == 0 && strcmp(u.code, l.code) == 0) {
printf("登录成功\n");
return 0; // 登录成功
}
}
fclose(fp);
printf("登录失败\n");
return 0;
}
log.h
#ifndef _LOG_H_
#define _LOG_H_
#include<myhead.h>
typedef struct
{
char user[20];
char code[20];
}user;
int login();
int regist();
#endif
my.c
#include "log.h"
int main(int argc, const char *argv[])
{
int ch;
while(1){
printf("\t\t\t1.注册\n");
printf("\t\t\t2.登录\n");
printf("\t\t\t3.退出\n");
printf("输入你的选择:\n");
scanf("%d",&ch);
getchar();//吸收多余的换行符:
switch(ch){
case 1:
regist();
break;
case 2:
login();
break;
case 3:
exit(EXIT_SUCCESS);
break;
default:
break;
}
}
return 0;
}