我试图在linux系统和gcc-4.7编译器上获取用户名和密码,如下所示:
#include "stdio.h"
#include "stdlib.h"
#include <termios.h>
#include <unistd.h>
void getuserdata(char *passwd)
{
struct termios term, term_orig;
tcgetattr(STDIN_FILENO, &term);
term_orig = term;
term.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &term);
scanf("%s", passwd);
/* Remember to set back, or your commands won't echo! */
tcsetattr(STDIN_FILENO, TCSANOW, &term_orig);
}
int main()
{
char *password, *username;
printf("Enter username: ");
scanf("%s", username);
fflush(stdin);
printf("\n");
printf("\nEnter password: ");
getuserdata(password);
printf("Entered username is:%s\n", username);
printf("Entered password is:%s\n", password);
return 0;
}
和预期的行为如下:
Enter username: test
Enter password:
Entered username is: test
Entered password is: xxxx
但它不起作用,并将null作为用户名或密码。
伙计我哪里错了?
非常感谢任何帮助。
感谢。
答案 0 :(得分:3)
您没有为username
和password
分配内存。
char *password, *username;
username = malloc(50);
printf("Enter username: ");
scanf("%49s", username);
printf("\n");
printf("\nEnter password: ");
password = malloc(50);
getuserdata(password);