Linux系統(tǒng)下解決getch()輸入數(shù)值不回顯示問(wèn)題
在linux系統(tǒng)下開發(fā)C 程序卻會(huì)遇到系統(tǒng)不支持conio.h頭文件,無(wú)法使用getch()不回顯函數(shù)。下面就演示如何構(gòu)建函數(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,則關(guān)閉回顯,為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用于獲得用戶輸入的密碼,并將其存儲(chǔ)在指定的字符數(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();//將回車符屏蔽掉 //首先關(guān)閉輸出回顯,這樣輸入密碼時(shí)就不會(huì)顯示輸入的字符信息 set_disp_mode(STDIN_FILENO,0); //調(diào)用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; }
運(yùn)行結(jié)果:
說(shuō)明:Linux下C編程遇到要輸入密碼的問(wèn)題,可輸入的時(shí)候密碼總不能讓人看見(jiàn)吧,本來(lái)想用getch()來(lái)解決輸入密碼無(wú)回顯的問(wèn)題的,不料Linux-C中不支持getch(),我也沒(méi)有找到功能類似的函數(shù)代替,上面這個(gè)例子達(dá)到了預(yù)期的效果。
PS:linux getch()實(shí)現(xiàn)代碼如下所示:
#include <termio.h> int getch(void) { struct termios tm, tm_old; int fd = 0, ch; if (tcgetattr(fd, &tm) < 0) {//保存現(xiàn)在的終端設(shè)置 return -1; } tm_old = tm; cfmakeraw(&tm);//更改終端設(shè)置為原始模式,該模式下所有的輸入數(shù)據(jù)以字節(jié)為單位被處理 if (tcsetattr(fd, TCSANOW, &tm) < 0) {//設(shè)置上更改之后的設(shè)置 return -1; } ch = getchar(); if (tcsetattr(fd, TCSANOW, &tm_old) < 0) {//更改設(shè)置為最初的樣子 return -1; } return ch; }
總結(jié)
以上所述是小編給大家介紹的Linux系統(tǒng)下解決getch()輸入數(shù)值不回顯示問(wèn)題,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
國(guó)產(chǎn)中文操作系統(tǒng)OpenDesktop
國(guó)產(chǎn)中文操作系統(tǒng)OpenDesktop...2006-10-10Linux下Oracle中SqlPlus時(shí)上下左右鍵亂碼問(wèn)題的解決辦法
這篇文章主要介紹了Linux下Oracle中SqlPlus時(shí)上下左右鍵亂碼問(wèn)題的解決辦法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-01-01Linux環(huán)境中使用Ext3文件系統(tǒng)
Linux環(huán)境中使用Ext3文件系統(tǒng)...2006-10-10Linux下安裝mysql 5.7.17.tar.gz的教程詳解
這篇文章主要介紹了Linux下安裝mysql 5.7.17.tar.gz的教程詳解,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-04-04