Linux密码输入回显星号

来源:互联网 发布:tensorflow 用什么语言 编辑:程序博客网 时间:2024/05/16 09:19

在Linux中,使用getch()很麻烦,以下是我搜集到的密码输入回显星号的代码,亲测好用!


[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. #include<stdio.h>  
  2. #include<termios.h>  
  3. #include<unistd.h>  
  4. #include<assert.h>  
  5. #include<string.h>  
  6. #include <stdlib.h>  
  7. int getch()  
  8. {  
  9.     int c=0;  
  10.     struct termios org_opts, new_opts;  
  11.     int res=0;  
  12.     //-----  store old settings -----------  
  13.     res=tcgetattr(STDIN_FILENO, &org_opts);  
  14.     assert(res==0);  
  15.     //---- set new terminal parms --------  
  16.     memcpy(&new_opts, &org_opts, sizeof(new_opts));  
  17.     new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);  
  18.     tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);  
  19.     c=getchar();  
  20.     //------  restore old settings ---------  
  21.     res=tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);  
  22.     assert(res==0);  
  23.     return c;  
  24. }  
  25.   
  26. int  main()  
  27. {  
  28.     int i;  
  29.     char *pd = (char *)malloc(sizeof(char) * 128);  
  30.   
  31.     for(i = 0; ; i++)  
  32.     {  
  33.     pd[i] = getch();  
  34.   
  35.     if(pd[i] == '\n')  
  36.     {  
  37.         pd[i] = '\0';  
  38.   
  39.         break;  
  40.     }  
  41.   
  42.     if(pd[i] == 127) //删除  
  43.     {  
  44.         printf("\b \b");  
  45.   
  46.         i = i - 2;  
  47.     }  
  48.     else  
  49.     {  
  50.         printf("*");  
  51.     }  
  52.     if(i<0)  
  53.     {  
  54.         pd[0]='\0';  
  55.     }  
  56.     }  
  57.       
  58.     printf("\ncode:%s\n",pd);  
  59.     return 0;  
  60. }  



0 0
原创粉丝点击