C语言输入密码时,用 * 隐藏

C语言输入密码时,用 * 隐藏

包含两个平台,windows和linux

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #ifndef _WIN32                   //Linux platform
 4 #include <termio.h>
 5 #ifndef STDIN_FILENO
 6 #define STDIN_FILENO 0
 7 #endif
 8 
 9 int getch(void)
10 {
11     struct termios tm, tm_old;
12     int fd = STDIN_FILENO, c;
13     if(tcgetattr(fd, &tm) < 0)
14         return -1;
15     tm_old = tm;
16     cfmakeraw(&tm);
17     if(tcsetattr(fd, TCSANOW, &tm) < 0)
18         return -1;
19     c = fgetc(stdin);
20     if(tcsetattr(fd, TCSANOW, &tm_old) < 0)
21         return -1;
22     return c;
23 }
24 
25 #else                            //WIN32 platform
26 #include <conio.h>
27 #endif
28 
29 
30 #define MAX_LEN   8
31 #define BACKSPACE 8
32 #define ENTER     13
33 #define ALARM     7
34 
35 char *getPasswd(const char *prompt)
36 {
37     int i=0, ch;
38     static char p[MAX_LEN+1]="";
39     printf("%s", prompt);
40     while((ch = getch())!= -1 && ch != ENTER)
41     {
42         if(i == MAX_LEN && ch != BACKSPACE)
43         {
44             putchar(ALARM);
45             continue;
46         }
47         if(ch == BACKSPACE)
48         {
49             if(i==0)
50             {
51                 putchar(ALARM);
52                 continue;
53             }
54             i--;
55             putchar(BACKSPACE);
56             putchar(' ');
57             putchar(BACKSPACE);
58         }
59         else
60         {
61             p[i] = ch;
62             putchar('*');
63             i++;
64         }
65     }
66 
67     if(ch == -1)
68     {
69         while(i != -1)
70         {
71             p[i--] = '\0';
72         }
73         return NULL;
74     }
75     p[i]='\0';
76     printf("\n");
77     return p;
78 }
79 
80 
81 int main()
82 {
83     char *pw = getPasswd("passwd:");
84     puts(pw);
85     puts("clearing the static buffer with 0 ...");
86     while(*pw)
87     {
88         *pw++=0;
89     }
90     pw=NULL;
91     system("pause");
92     return 0;
93 }
posted @ 2014-07-17 16:16  一路向西  阅读(2907)  评论(0编辑  收藏  举报