原文:http://blog.chinaunix.net/uid-20754793-id-177771.html
linux C 下没有getch()函数,于是上网查了查资料,
发现可以C语言可通过使用tcgetattr函数和tcsetattr函数来实现
/* Standard C header */
#include <stdio.h> /* for getchar(), printf() */
/* POSIX headers */
#include <termios.h> /* for tcxxxattr, ECHO, etc */
#include <unistd.h> /* for STDIN_FILENO */
#define LENGTH 8 /*Password length */
int main(void)
{
char password[LENGTH];
int len = 0;
int ch;
struct termios oldt, newt;
printf("please input you password:");
while (1) {
if (len < LENGTH) {
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ECHO | ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
printf("*");
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
} else {
printf("\nPassword must less then 8\n");
break;
}
len = len + 1;
}
return 0;
}
#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,贴一个网站大家看下
http://www.tsnc.edu.cn/default/tsnc_wgrj/doc/curses.html
SHELL实现不回显
(1)方法就是:
stty -echo #设置输入字符不回显
#此处用read语句接收用户输入的内容
stty echo #取消不回显状态
#!/bin/bash
passwd=""
echo -n "Please input password:"
stty -echo
read passwd
echo
stty echo
echo "The password is $passwd"
(2)其实shell中的 read的-s选项直接就可以实现输入内容不回显。如下实现
#!/bin/bash
passwd=""
echo -n "Please input password:"
read -s passwd
echo
echo "The password is $passwd"