关闭STDIN_FILE或者其他fd的ECHO回显cgetattr函数和tcsetattr函数

来源:互联网 发布:offcf2007修复软件 编辑:程序博客网 时间:2024/05/21 06:20
使用tcgetattr函数和tcsetattr函数
  还有种方法,可以不使用curses库解决密码输入的回显问题。程序p6.4.c通过使用tcgetattr函数和tcsetattr函数同样达到了目的。具体代码如下:
  #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 passwd[20];//首先关闭输出回显,这样输入密码时就不会显示输入的字符信息
    set_disp_mode(STDIN_FILENO,0);//调用getpasswd函数获得用户输入的密码
    getpasswd(passwd, sizeof(passwd));

    printf("/nYour passwd is:%s/n", passwd);
    printf("Press any key continue ……/n");

    set_disp_mode(STDIN_FILENO,1);
    getchar();
    return 0;
  }
  使用gcc编译p6.4.c代码,获得名为p6.4的可执行程序。执行该程序,得到如下的输出结果:
  [program@localhost charter6]$ gcc -o p6.4 p6.4.c 
  [program@localhost charter6]$ ./p6.4 Please Input 
  password:
  Your passwd is:

  afdfasf Press any key continue ……

  [program@localhost charter6]$

 

 原文地址http://book.chinaitlab.com/linux/777386.html

原创粉丝点击