2014-01-24 55 views

回答

3

您可以通过getpass帮助做到这一点。但是man getpass

此功能已过时。不要使用它。如果要在未启用终端回显的情况下读取输入,请参阅termios(3)中ECHO标志的说明。

这段代码就可以了(此代码是其他SO后精确副本)

#include <stdio.h> 
#include <stdlib.h> 
#include <termios.h> 
#include <string.h> 
int main(int argc, char **argv) 
{ 
    struct termios oflags, nflags; 
    char password[128]; 

    tcgetattr(fileno(stdin), &oflags); 
    nflags = oflags; 
    nflags.c_lflag &= ~ECHO; 
    nflags.c_lflag |= ECHONL; 

    if (tcsetattr(fileno(stdin), TCSADRAIN, &nflags) != 0) { 
     perror("tcsetattr"); 
     return -1; 
    } 
    printf("\npassword(Echo Disabled) : "); 
    fgets(password, sizeof(password), stdin); 
    password[strlen(password) - 1] = 0; 
    printf("Entered password  : %s\n", password); 

    if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { 
     perror("tcsetattr"); 
     return -1; 
    } 

    printf("\npassword(Echo Enabled) : "); 
    fgets(password, sizeof(password), stdin); 
    password[strlen(password) - 1] = 0; 
    printf("Entered password  : %s\n", password); 

    return 0; 
} 

Explantion:

  1. 获取使用tcgetattr()用于恢复终端在termios structure终端当前属性更新的属性。
  2. 创建新的termios structure并在termios structure成员中设置禁用回显标志。
  3. 使用tcsetattr从新的termios structure中设置新的终端属性。
  4. 如果要启用回显,请使用tcsetattr再次设置旧保存的终端属性。即恢复终端到原来的状态

Further detail man tcgetattr

+0

感谢您让我避免使用过时的方法! – Nullpointer

+0

在使用之前,请务必阅读系统调用的手册页。 – sujin

0

您可以使用getpass

#include <unistd.h> 
... 
char *password = getpass("Password: "); 
... 
+0

谢谢!这工作! – Nullpointer

0

使用了getpass()或另一种方式是低于

#include <stdio.h> 
#include <stdlib.h> 
#include <termios.h> 

int 
main(int argc, char **argv) 
{ 
    struct termios oflags, nflags; 
    char password[64]; 

    /* disabling echo */ 
    tcgetattr(fileno(stdin), &oflags); 
    nflags = oflags; 
    nflags.c_lflag &= ~ECHO; 
    nflags.c_lflag |= ECHONL; 

    if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) { 
     perror("tcsetattr"); 
     return EXIT_FAILURE; 
    } 

    printf("password: "); 
    fgets(password, sizeof(password), stdin); 
    password[strlen(password) - 1] = 0; 
    printf("you typed '%s'\n", password); 

    /* restore terminal */ 
    if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) { 
     perror("tcsetattr"); 
     return EXIT_FAILURE; 
    } 

    return 0; 
} 
相关问题