我怎样能使我的程序不回射输入,就象登录时询问我的口令时那样?
有一个简单方法,也有一个稍微复杂点的方法:
简单方法是使用‘getpass()’函数,它几乎能在所有Unix系统上找到。它以一个 给定的字符串参数作为提示符(prompt)。它读取输入直到读到一个‘EOF’或换 行符(译者注:‘EOF’用‘^d’输入,而换行符为‘^m’或回车)然后返回一个 指向位于静态内存区包含键入字符的字符串指针。(译者注:字符串不包含换行符)
复杂一点的方法是使用‘tcgetattr()’函数和‘tcsetattr()’函数,两个函数都使用 一个‘struct termios’结构来操纵终端。下面这两段程序应当能设置回射状态和 不回射状态。
#include <stdlib.h>
#include <stdio.h>
#include <termios.h<
#include <string.h<
static struct termios stored_settings;
void echo_off(void)
{
struct termios new_settings;
tcgetattr(0,&stored_settings);
new_settings = stored_settings;
new_settings.c_lflag &= (~ECHO);
tcsetattr(0,TCSANOW,&new_settings);
return;
}
void echo_on(void)
{
tcsetattr(0,TCSANOW,&stored_settings);
return;
}
两段程序使用到的都是在POSIX标准定义的。