Unix cシステム関数で実現された登録ログインモジュール

16117 ワード

 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!
"); 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!
"); 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!
",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!
"); 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
"); 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!
"); 82 } 83 84 int main() 85 { 86 printf("1,reg\t\t2,login
"); 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
"); 95 break; 96 } 97 return 0; 98 }