用unix c系统函数实现的的注册登录模块

 1 /* 登录模块,密码放在pass.db中*/
 2 #include <stdio.h>
 3 #include <unistd.h>
 4 #include <fcntl.h>
 5 #include <stdlib.h>
 6 #include <string.h>
 7 #include <stdbool.h>
 8 
 9 typedef struct Person{
10     char name[20];
11     char pass[20];
12 }Person;
13 
14 void reg()
15 {
16     char name[20];
17     printf("Please input your name:");
18     scanf("%s",name);
19     int fd = open("pass.db",O_CREAT|O_RDWR|O_APPEND,0666);
20     if(fd == -1){
21         printf("Cannot open pass.db!\n");
22         exit(-1);
23     }
24     int n = sizeof(Person);
25     char tmp[n];
26     //判断是否存在该用户名 
27     while(read(fd,tmp,sizeof(Person)) == sizeof(Person)){
28         if(!strncmp(tmp,name,19)){
29             printf("This name had been registerwd!"
30                     "please try anthor one!\n");
31             printf("Now please enter the name you want:");
32             scanf("%s",name);
33             lseek(fd,0,SEEK_SET);// 输入新的name 后 从文件头开始比对
34         }
35     }
36     printf("Congratulations,%s is avilable!\n",name);
37     printf("Now,please enter the password:");
38     char pass[20];
39     char check[20];
40     scanf("%s",pass);
41     printf("Check the password:");
42     scanf("%s",check);
43     while(strcmp(pass,check)){
44         printf("I'm sorry,you entered different password!\n");
45         printf("Please enter another  password:");
46         scanf("%s",pass);
47         printf("Check the password:");
48         scanf("%s",check);
49     }
50     Person regPerson;
51     strcpy(regPerson.name,name);
52     strcpy(regPerson.pass,pass);
53     lseek(fd,0,SEEK_END);
54     write(fd,&regPerson,sizeof(Person));
55     close(fd);
56 }
57 
58 void confirm()
59 {
60     bool flag =false;
61     int fd = open("pass.db",O_RDONLY);
62     if(fd == -1){
63         printf("FILE \"pass.db\" OPENED FAILED\n");
64         exit(-2);
65     }
66     Person tmp;
67     char name[20]={0};
68     char pass[20]={0};
69     printf("\tName:");
70     scanf("%s",name);
71     while(read(fd,&tmp,sizeof(tmp)) == sizeof(tmp)){
72         if(!strncmp(name,tmp.name,20)){
73             while(strncmp(pass,tmp.name+20,20)){
74                 printf("\tPassword:");
75                 scanf("%s",pass);
76             }
77             flag = true;
78         }
79     }
80     if(flag)
81         printf("sucess!\n");
82 }
83 
84 int main()
85 {
86     printf("1,reg\t\t2,login\n");
87     int select;
88     scanf("%d",&select);
89     switch(select){
90         case 1:reg();
91                break;
92         case 2:confirm();
93                break;
94         default:printf("ERROR INPUT\n");
95                 break;
96     }
97     return 0;
98 }

 

你可能感兴趣的:(unix)