使用tcgetattr函數和tcsetattr函數 解決密碼回顯問題。

來源:互聯網
上載者:User

使用tcgetattr函數和tcsetattr函數

還有種方法,可以不使用curses庫解決密碼輸入的回顯問題。程式p6.4.c通過使用tcgetattr函數和tcsetattr函數同樣達到了目的。具體代碼如下:

    

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>

#define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL)

//函數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;
}

//函數getpasswd用於獲得使用者輸入的密碼,並將其儲存在指定的字元數組中
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 passwd[20];

//首先關閉輸出回顯,這樣輸入密碼時就不會顯示輸入的字元資訊
set_disp_mode(STDIN_FILENO,0);
//調用getpasswd函數獲得使用者輸入的密碼
getpasswd(passwd, sizeof(passwd));

printf("/nYour passwd is:%s/n", passwd);
printf("Press any key continue .../n");

set_disp_mode(STDIN_FILENO,1);
getchar();
return 0;
}

使用gcc編譯p6.4.c代碼,獲得名為p6.4的可執行程式。執行該程式,得到如下的輸出結果:

    

[program@localhost charter6]$ gcc -o p6.4 p6.4.c
[program@localhost charter6]$ ./p6.4
Please Input password:
Your passwd is:afdfasf

Press any key continue ...

[program@localhost charter6]$

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.