码迷,mamicode.com
首页 > 系统相关 > 详细

linux系统下解决getch()输入数值不回显示

时间:2017-11-09 00:14:41      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:src   效果   http   str   inux   .com   getch   字符   实现   

  在linux系统下开发C 程序却会遇到系统不支持conio.h头文件,无法使用getch()不回显函数。下面就演示如何构建函数实现数值输入不回显。

  1 #include <stdio.h>  
  2 
  3 #include <termios.h>  
  4 
  5 #include <unistd.h>  
  6 
  7 #include <errno.h>  
  8 
  9 #define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL)  
 10 
 11 //函数set_disp_mode用于控制是否开启输入回显功能  
 12 
 13 //如果option为0,则关闭回显,为1则打开回显  
 14 
 15 int set_disp_mode(int fd,int option)  
 16 
 17 {  
 18 
 19    int err;  
 20 
 21    struct termios term;  
 22 
 23    if(tcgetattr(fd,&term)==-1){  
 24 
 25      perror("Cannot get the attribution of the terminal");  
 26 
 27      return 1;  
 28 
 29    }  
 30 
 31    if(option)  
 32 
 33         term.c_lflag|=ECHOFLAGS;  
 34 
 35    else  
 36 
 37         term.c_lflag &=~ECHOFLAGS;  
 38 
 39    err=tcsetattr(fd,TCSAFLUSH,&term);  
 40 
 41    if(err==-1 && err==EINTR){  
 42 
 43         perror("Cannot set the attribution of the terminal");  
 44 
 45         return 1;  
 46 
 47    }  
 48 
 49    return 0;  
 50 
 51 }  
 52 
 53 //函数getpasswd用于获得用户输入的密码,并将其存储在指定的字符数组中  
 54 
 55 int getpasswd(char* passwd, int size)  
 56 
 57 {  
 58 
 59    int c;  
 60 
 61    int n = 0;  
 62 
 63     
 64 
 65    printf("Please Input password:");  
 66 
 67     
 68 
 69    do{  
 70 
 71       c=getchar();  
 72 
 73       if (c != \n|c!=\r){  
 74 
 75          passwd[n++] = c;  
 76 
 77       }  
 78 
 79    }while(c != \n && c !=\r && n < (size - 1));  
 80 
 81    passwd[n] = \0;  
 82 
 83    return n;  
 84 
 85 }  
 86 
 87 int main()  
 88 
 89 {  
 90 
 91    char *p,passwd[20],name[20];  
 92 
 93    printf("Please Input name:");  
 94 
 95    scanf("%s",name);  
 96 
 97    getchar();//将回车符屏蔽掉  
 98 
 99    //首先关闭输出回显,这样输入密码时就不会显示输入的字符信息  
100 
101    set_disp_mode(STDIN_FILENO,0);  
102 
103    //调用getpasswd函数获得用户输入的密码  
104 
105    getpasswd(passwd, sizeof(passwd));    
106 
107    p=passwd;  
108 
109    while(*p!=\n)  
110 
111      p++;  
112 
113    *p=\0;  
114 
115    printf("\nYour name is: %s",name);  
116 
117    printf("\nYour passwd is: %s\n", passwd);  
118 
119    printf("Press any key continue ...\n");  
120 
121    set_disp_mode(STDIN_FILENO,1);  
122 
123    getchar();  
124 
125    return 0;  
126 
127 }  
128 
129  
130 
131  
132 
133  

运行结果:

技术分享

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

linux系统下解决getch()输入数值不回显示

标签:src   效果   http   str   inux   .com   getch   字符   实现   

原文地址:http://www.cnblogs.com/binglmm/p/7806936.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!