Linux 环境下C语言下实现密码输入无回显

[cpp]  view plain copy
  1. #include <stdio.h>  
  2. #include <termios.h>  
  3. #include <unistd.h>  
  4. #include <errno.h>  
  5. #define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL)  
  6. //函数set_disp_mode用于控制是否开启输入回显功能  
  7. //如果option为0,则关闭回显,为1则打开回显  
  8. int set_disp_mode(int fd,int option)  
  9. {  
  10.    int err;  
  11.    struct termios term;  
  12.    if(tcgetattr(fd,&term)==-1){  
  13.      perror("Cannot get the attribution of the terminal");  
  14.      return 1;  
  15.    }  
  16.    if(option)  
  17.         term.c_lflag|=ECHOFLAGS;  
  18.    else  
  19.         term.c_lflag &=~ECHOFLAGS;  
  20.    err=tcsetattr(fd,TCSAFLUSH,&term);  
  21.    if(err==-1 && err==EINTR){  
  22.         perror("Cannot set the attribution of the terminal");  
  23.         return 1;  
  24.    }  
  25.    return 0;  
  26. }  
  27. //函数getpasswd用于获得用户输入的密码,并将其存储在指定的字符数组中  
  28. int getpasswd(char* passwd, int size)  
  29. {  
  30.    int c;  
  31.    int n = 0;  
  32.     
  33.    printf("Please Input password:");  
  34.     
  35.    do{  
  36.       c=getchar();  
  37.       if (c != '\n'|c!='\r'){  
  38.          passwd[n++] = c;  
  39.       }  
  40.    }while(c != '\n' && c !='\r' && n < (size - 1));  
  41.    passwd[n] = '\0';  
  42.    return n;  
  43. }  
  44. int main()  
  45. {  
  46.    char *p,passwd[20],name[20];  
  47.    printf("Please Input name:");  
  48.    scanf("%s",name);  
  49.    getchar();//将回车符屏蔽掉  
  50.    //首先关闭输出回显,这样输入密码时就不会显示输入的字符信息  
  51.    set_disp_mode(STDIN_FILENO,0);  
  52.    //调用getpasswd函数获得用户输入的密码  
  53.    getpasswd(passwd, sizeof(passwd));    
  54.    p=passwd;  
  55.    while(*p!='\n')  
  56.      p++;  
  57.    *p='\0';  
  58.    printf("\nYour name is: %s",name);  
  59.    printf("\nYour passwd is: %s\n", passwd);  
  60.    printf("Press any key continue ...\n");  
  61.    set_disp_mode(STDIN_FILENO,1);  
  62.    getchar();  
  63.    return 0;  
  64. }  

运行结果:


说明:Linux下C编程遇到要输入密码的问题,可输入的时候密码总不能让人看见吧,本来想用getch()来解决输入密码无回显的问题的,不料Linux-C中不支持getch(),我也没有找到功能类似的函数代替,上面这个例子达到了预期的效果。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值