分类: C/C++
2008-09-21 11:35:23
#include
#ifndef _WIN32 //Linux platform
#include
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
int getch(void)
{
struct termios tm, tm_old;
int fd = STDIN_FILENO, c;
if(tcgetattr(fd, &tm) < 0)
return -1;
tm_old = tm;
cfmakeraw(&tm);
if(tcsetattr(fd, TCSANOW, &tm) < 0)
return -1;
c = fgetc(stdin);
if(tcsetattr(fd, TCSANOW, &tm_old) < 0)
return -1;
return c;
}
#else //WIN32 platform
#include
#endif
#define MAX_LEN 8
#define BACKSPACE 8
#define ENTER 13
#define ALARM 7
char *getPasswd(const char *prompt)
{
int i=0, ch;
static char p[MAX_LEN+1]="";
printf("%s", prompt);
while((ch = getch())!= -1 && ch != ENTER)
{
if(i == MAX_LEN && ch != BACKSPACE)
{
putchar(ALARM);
continue;
}
if(ch == BACKSPACE)
{
if(i==0)
{
putchar(ALARM);
continue;
}
i--;
putchar(BACKSPACE);
putchar(' ');
putchar(BACKSPACE);
}
else
{
p[i] = ch;
putchar('*');
i++;
}
}
if(ch == -1)
{
while(i != -1)
{
p[i--] = '\0';
}
return NULL;
}
p[i]='\0';
printf("\n");
return p;
}
int main()
{
char *pw = getPasswd("passwd:");
puts(pw);
puts("clearing the static buffer with 0 ...");
while(*pw)
{
*pw++=0;
}
pw=NULL;
return 0;
}