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 }

转载于:https://www.cnblogs.com/love--wenxing/p/3851364.html

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值