I am writing a small C program that asks a user for a password, as the user enters characters via keyboard, these characters will be displayed as asterisks and when they hit enter the actual password is displayed. I have tried fiddling with getchar() and assigning variables but I am not getting the desired solution. Any guidance is appreciated, thanks.
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <string.h>
char *get_password();
int main() {
struct termios info;
tcgetattr(0, &info);
// info.c_lflag &= ~ECHO;
tcsetattr(0, TCSANOW, &info);
printf("Create a password: ");
int c = getchar();
c = '*';
char *password = get_password();
printf("You entered: %s\n", password);
tcgetattr(0, &info);
info.c_lflag |= ECHO;
tcsetattr(0, TCSANOW, &info);
}
#define BUFSIZE 100
char buf[BUFSIZE];
char *get_password() {
int c, len = 0;
while ((c = getchar()) != EOF && c != '\n') {
buf[len++] = c;
if (len == BUFSIZE - 1)
break;
}
buf[len] = 0;
putchar('\n');
return buf;
}