Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15451250
  • 博文数量: 2005
  • 博客积分: 11986
  • 博客等级: 上将
  • 技术积分: 22535
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-17 13:56
文章分类

全部博文(2005)

文章存档

2014年(2)

2013年(2)

2012年(16)

2011年(66)

2010年(368)

2009年(743)

2008年(491)

2007年(317)

分类:

2010-10-13 14:28:31

使用tcgetattr函数和tcsetattr函数
  还有种方法,可以不使用curses库解决密码输入的回显问题。程序p6.4.c通过使用tcgetattr函数和tcsetattr函数同样达到了目的。具体代码如下:
  #include  
  #include  
  #include  
  #include  
  #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]$
阅读(1876) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

2011-05-22 15:21:42

学习了,多谢楼主分享哦!也欢迎广大linux爱好者来我的论坛一起讨论arm哦!www.lt-net.cn