你的位置:首页 > 软件开发 > 操作系统 > linux系统下解决getch()输入数值不回显示

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

发布时间:2017-11-09 00:00:23
在linux系统下开发C 程序却会遇到系统不支持conio.h头文件,无法使用getch()不回显函数。下面就演示如何构建函数实现数值输入不回显。 1 #include <stdio.h> 2 3 #include <termios.h> 4 5 ...

linux系统下解决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系统下解决getch()输入数值不回显示

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

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

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

关键词:linux

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录