`
夜不懂白的黑
  • 浏览: 19276 次
  • 性别: Icon_minigender_1
  • 来自: 孝感
社区版块
存档分类
最新评论

Unix/Linux下实现命令行输入以*回显

阅读更多

 

在linux/Unix命令行下执行一个程序,将输入以*号回显出来,类似于登录时输入密码以*代替。
(Windows下很好实现,可以结合使用getch()和putchar(),但是getch()不是标准C函数,linux/Unix下没有,需要写一个函数实现getch()),好了直接上代码
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include "Base64.c"  //Base64编码程序

int getch(void);

main()
{
        char str1[20],str2[60];
        char ch;
        int i=0;
        printf("Please enter your password: ");
        while((ch=getch())!=13 ) //按回车键退出
        {
          str1[i++]=ch;
          putchar('*');
        }
        str1[i]='\0';
        printf("\n Your input is: %s\n",str1);
        strcpy(str2,base64_encode(base64_encode(str1)));
        printf("Encoding string is: %s\n",str2);
     
}
//参考http://blog.csdn.net/liuchao35758600/article/details/6419499
int getch(void)
{
        struct termios tm, tm_old;
        int fd = STDIN_FILENO, c;
        if(tcgetattr(fd, &tm) < 0) 
        return -1; 
        tm_old = tm;
        cfmakeraw(&tm);
        if(tcsetattr(fd, TCSANOW, &tm) < 0)
                return -1;
        c = fgetc(stdin);
        if(tcsetattr(fd, TCSANOW, &tm_old) < 0)
                return -1;
        if(c == 3) exit(1);  //按Ctrl+C结束退出
        return c; 
}

 有兴趣可以研究下Unix下的一个头文件curses.h,贴一个网站大家看下


更正下:改方法只能实现Linux下的星号显示,对于Unix会有点问题!谢谢
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics