Created
September 15, 2017 21:20
-
-
Save kana-ph/c7c807cad0500c656d82fd4dfb63e77e to your computer and use it in GitHub Desktop.
Password input from stdin using curse getch()
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
#include <stdio.h> | |
#include <string.h> | |
#include <termios.h> | |
#include <unistd.h> | |
int getch(); | |
const char ENTER_KEY = '\n'; | |
const char BACKSPACE_KEY = (char) 127; | |
char *get_password() { | |
char buffer[160]; | |
char read; | |
int index = 0; | |
read = (char) getch(); | |
while (ENTER_KEY != read) { | |
if (BACKSPACE_KEY == read) { | |
if (index > 0) { | |
printf("%s", "\b \b"); | |
index--; | |
} | |
} else { | |
buffer[index] = read; | |
index++; | |
printf("*"); | |
} | |
read = (char) getch(); | |
} | |
printf("\n"); | |
buffer[index] = '\0'; | |
return strdup(buffer); | |
} | |
int main() { | |
char *correct_password = "@(abcd123)"; | |
char *input_password; | |
int attempts = 0; | |
int max_attempts = 3; | |
int valid_password = 0; | |
while (attempts < max_attempts) { | |
printf("Enter password: "); | |
input_password = get_password(); | |
if (strcmp(correct_password, input_password) == 0) { | |
valid_password = 1; | |
break; | |
} | |
attempts++; | |
} | |
if (valid_password == 1) { | |
printf("PASSWORD CORRECT!"); | |
} else { | |
printf("%d INCORRECT PASSWORD ATTEMPTS", attempts); | |
} | |
printf("\n"); | |
return 0; | |
} | |
int getch() { | |
/* | |
* Copied from: | |
* https://stackoverflow.com/questions/3276546/how-to-implement-getch-function-of-c-in-linux#23035044 | |
*/ | |
struct termios oldattr, newattr; | |
int ch; | |
tcgetattr(STDIN_FILENO, &oldattr); | |
newattr = oldattr; | |
newattr.c_lflag &= ~(ICANON | ECHO); | |
tcsetattr(STDIN_FILENO, TCSANOW, &newattr); | |
ch = getchar(); | |
tcsetattr(STDIN_FILENO, TCSANOW, &oldattr); | |
return ch; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment