Created
February 11, 2019 23:04
-
-
Save theriverman/ee1a625bcb7b4ee363bb04329a1195e3 to your computer and use it in GitHub Desktop.
C++ password prompt with stdin masking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Example code: https://gist.github.com/theriverman/b41daa62f5013126b77790b8165fcf74 | |
ORIGINAL LOCATION OF CODE SNIPPET: | |
https://stackoverflow.com/questions/1413445/reading-a-password-from-stdcin | |
Credits: https://stackoverflow.com/users/121961/vargas | |
*/ | |
#ifdef WIN32 | |
#include <windows.h> | |
#else | |
#include <termios.h> | |
#include <unistd.h> | |
#endif | |
void SetStdinEcho(bool enable = true) | |
{ | |
#ifdef WIN32 | |
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); | |
DWORD mode; | |
GetConsoleMode(hStdin, &mode); | |
if( !enable ) | |
mode &= ~ENABLE_ECHO_INPUT; | |
else | |
mode |= ENABLE_ECHO_INPUT; | |
SetConsoleMode(hStdin, mode ); | |
#else | |
struct termios tty; | |
tcgetattr(STDIN_FILENO, &tty); | |
if( !enable ) | |
tty.c_lflag &= ~ECHO; | |
else | |
tty.c_lflag |= ECHO; | |
(void) tcsetattr(STDIN_FILENO, TCSANOW, &tty); | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment