在Linux进行登录是输入密码不会被回显,所以我也写了个简单的登入程序,使得在输入密码时不再进行回显。
#include <stdio.h> #include <stdlib.h> #include <termios.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <stdbool.h> #define USER_NAME "username" #define USER_PASS "userpass" #define MAX 20 #define ECHOFLAGS (ECHO | ECHOE | ECHOK) int set_disp_mode(int fd, int option) { int err; struct termios term; if (tcgetattr(fd, &term) == -1) { fprintf(stderr, "Can\'t get the attribution of the terminal!\n"); exit(1); } if (option) { term.c_lflag |= ECHOFLAGS; } else { term.c_lflag &= ~ECHOFLAGS; } err = tcsetattr(fd, TCSAFLUSH, &term); if (err == -1 && err == EINTR) { fprintf(stderr, "Can\'t set the attribution of the terminal!\n"); exit(1); } return 0; } int get_passwd(char* passwd, int size) { int c; int n = 0; fprintf(stderr, "Please input password:"); do { c = getchar(); if (c != '\n' && c != '\r') { passwd[n++] = c; } } while (c != '\n' && c != '\r' && n < (size-1)); passwd[n] = '\0'; return n; } bool check_login(const char* name, const char* passwd) { int nlen = strlen(USER_NAME); int plen = strlen(USER_PASS); return (strncmp(name, USER_NAME, nlen) == 0) && (strncmp(passwd, USER_PASS, plen) == 0); } int main(void) { char name[MAX]; char passwd[MAX]; LOGIN: fprintf(stderr, "login user:"); fgets(name, MAX, stdin); name[strlen(name)-1] = '\0'; set_disp_mode(STDIN_FILENO, 0); get_passwd(passwd, MAX); if (check_login(name, passwd)) { fprintf(stderr, "\nHello %s, Welcome!\n", name); } else { fprintf(stderr, "\n"); set_disp_mode(STDIN_FILENO, 1); goto LOGIN; } set_disp_mode(STDIN_FILENO, 1); return 0; }