Linux系統(tǒng)下解決getch()輸入數(shù)值不回顯示問題
在linux系統(tǒng)下開發(fā)C 程序卻會遇到系統(tǒng)不支持conio.h頭文件,無法使用getch()不回顯函數(shù)。下面就演示如何構建函數(shù)實現(xiàn)數(shù)值輸入不回顯。
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL)
//函數(shù)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;
}
//函數(shù)getpasswd用于獲得用戶輸入的密碼,并將其存儲在指定的字符數(shù)組中
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 *p,passwd[20],name[20];
printf("Please Input name:");
scanf("%s",name);
getchar();//將回車符屏蔽掉
//首先關閉輸出回顯,這樣輸入密碼時就不會顯示輸入的字符信息
set_disp_mode(STDIN_FILENO,0);
//調用getpasswd函數(shù)獲得用戶輸入的密碼
getpasswd(passwd, sizeof(passwd));
p=passwd;
while(*p!='\n')
p++;
*p='\0';
printf("\nYour name is: %s",name);
printf("\nYour passwd is: %s\n", passwd);
printf("Press any key continue ...\n");
set_disp_mode(STDIN_FILENO,1);
getchar();
return 0;
}
運行結果:

說明:Linux下C編程遇到要輸入密碼的問題,可輸入的時候密碼總不能讓人看見吧,本來想用getch()來解決輸入密碼無回顯的問題的,不料Linux-C中不支持getch(),我也沒有找到功能類似的函數(shù)代替,上面這個例子達到了預期的效果。
PS:linux getch()實現(xiàn)代碼如下所示:
#include <termio.h>
int getch(void)
{
struct termios tm, tm_old;
int fd = 0, ch;
if (tcgetattr(fd, &tm) < 0) {//保存現(xiàn)在的終端設置
return -1;
}
tm_old = tm;
cfmakeraw(&tm);//更改終端設置為原始模式,該模式下所有的輸入數(shù)據(jù)以字節(jié)為單位被處理
if (tcsetattr(fd, TCSANOW, &tm) < 0) {//設置上更改之后的設置
return -1;
}
ch = getchar();
if (tcsetattr(fd, TCSANOW, &tm_old) < 0) {//更改設置為最初的樣子
return -1;
}
return ch;
}
總結
以上所述是小編給大家介紹的Linux系統(tǒng)下解決getch()輸入數(shù)值不回顯示問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
國產(chǎn)中文操作系統(tǒng)OpenDesktop
國產(chǎn)中文操作系統(tǒng)OpenDesktop...2006-10-10
Linux下Oracle中SqlPlus時上下左右鍵亂碼問題的解決辦法
這篇文章主要介紹了Linux下Oracle中SqlPlus時上下左右鍵亂碼問題的解決辦法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-01-01
Linux環(huán)境中使用Ext3文件系統(tǒng)
Linux環(huán)境中使用Ext3文件系統(tǒng)...2006-10-10
用vi命令刪除日志中的所有內容并對日志進行實時監(jiān)控
2008-01-01
Linux下安裝mysql 5.7.17.tar.gz的教程詳解
這篇文章主要介紹了Linux下安裝mysql 5.7.17.tar.gz的教程詳解,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-04-04

