你好,游客 登录 注册 搜索
背景:
阅读新闻

Linux下解决getch()输入数值不回显示

[日期:2017-11-09] 来源:Linux社区  作者:binglmm [字体: ]

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

#include <stdio.h> 

#include <termios.h> 

#include <unistd.h> 

#include <errno.h> 

#define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL) 

//函数set_disp_mode用于控制是否开启输入回显功能 

//如果option为0,则关闭回显,为1则打开回显 

int set_disp_mode(int fd,int option) 

  int err; 

  struct termios term; 

  if(tcgetattr(fd,&term)==-1){ 

    perror("Cannot get the attribution of the terminal"); 

    return 1; 

  } 

  if(option) 

        term.c_lflag|=ECHOFLAGS; 

  else 

        term.c_lflag &=~ECHOFLAGS; 

  err=tcsetattr(fd,TCSAFLUSH,&term); 

  if(err==-1 && err==EINTR){ 

        perror("Cannot set the attribution of the terminal"); 

        return 1; 

  } 

  return 0; 

//函数getpasswd用于获得用户输入的密码,并将其存储在指定的字符数组中 

int getpasswd(char* passwd, int size) 

  int c; 

  int n = 0; 

   

  printf("Please Input password:"); 

   

  do{ 

      c=getchar(); 

      if (c != '\n'|c!='\r'){ 

        passwd[n++] = c; 

      } 

  }while(c != '\n' && c !='\r' && n < (size - 1)); 

  passwd[n] = '\0'; 

  return n; 

int main() 

  char *p,passwd[20],name[20]; 

  printf("Please Input name:"); 

  scanf("%s",name); 

  getchar();//将回车符屏蔽掉 

  //首先关闭输出回显,这样输入密码时就不会显示输入的字符信息 

  set_disp_mode(STDIN_FILENO,0); 

  //调用getpasswd函数获得用户输入的密码 

  getpasswd(passwd, sizeof(passwd));   

  p=passwd; 

  while(*p!='\n') 

    p++; 

  *p='\0'; 

  printf("\nYour name is: %s",name); 

  printf("\nYour passwd is: %s\n", passwd); 

  printf("Press any key continue ...\n"); 

  set_disp_mode(STDIN_FILENO,1); 

  getchar(); 

  return 0; 

}

运行结果:

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

本文永久更新链接地址http://www.linuxidc.com/Linux/2017-11/148425.htm

linux
相关资讯       Linux getch() 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款