Auch wenn dies eine sehr alte Frage ist, die bereits beantwortet wurde, hier ist, was ich verwendet habe (was der akzeptierten Antwort sehr ähnlich ist):
#include <termios.h>
#include <cstdio>
//
// The following is a slightly modifed version taken from:
// http://www.gnu.org/software/libc/manual/html_node/getpass.html
//
ssize_t my_getpass (char *prompt, char **lineptr, size_t *n, FILE *stream)
{
struct termios _old, _new;
int nread;
/* Turn echoing off and fail if we can’t. */
if (tcgetattr (fileno (stream), &_old) != 0)
return -1;
_new = _old;
_new.c_lflag &= ~ECHO;
if (tcsetattr (fileno (stream), TCSAFLUSH, &_new) != 0)
return -1;
/* Display the prompt */
if (prompt)
printf("%s", prompt);
/* Read the password. */
nread = getline (lineptr, n, stream);
/* Remove the carriage return */
if (nread >= 1 && (*lineptr)[nread - 1] == '\n')
{
(*lineptr)[nread-1] = 0;
nread--;
}
printf("\n");
/* Restore terminal. */
(void) tcsetattr (fileno (stream), TCSAFLUSH, &_old);
return nread;
}
//
// Test harness - demonstrate calling my_getpass().
//
int main(int argc, char *argv[])
{
size_t maxlen = 255;
char pwd[maxlen];
char *pPwd = pwd; // <-- haven't figured out how to avoid this.
int count = my_getpass((char*)"Enter Password: ", &pPwd, &maxlen, stdin);
printf("Size of password: %d\nPassword in plaintext: %s\n", count, pwd);
return 0;
}
4 Stimmen
Es gibt keinen portablen Weg - dies hängt stark von Ihrer Plattform ab.
1 Stimmen
@Jerry, das ist es nicht wert... auch wenn es LEGACY ist, ist es die tragbarste Art und Weise, es zu tun.
0 Stimmen
@MichaelAaronSafyan Ich stimme zu. Es ist eine seltsame Entscheidung zu treffen
getpass()
veraltet und sogar aus POSIX entfernt, ohne eine Alternative anzubieten (wie NetBSDsgetpass_r()
). Jetzt macht jeder seine eigene Version, die mit Sicherheits-, Nutzbarkeits- und Portabilitätsfehlern behaftet ist.