Chinaunix首页 | 论坛 | 博客
  • 博客访问: 97214
  • 博文数量: 20
  • 博客积分: 2000
  • 博客等级: 大尉
  • 技术积分: 294
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-24 10:29
文章分类

全部博文(20)

文章存档

2010年(2)

2009年(1)

2008年(17)

我的朋友

分类: 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;
}

阅读(2871) | 评论(4) | 转发(0) |
给主人留下些什么吧!~~

青年就是我2013-10-22 18:02:53

在linux ubuntu 测试过 可以用 赞赞!!!!!!

青年就是我2013-10-22 18:02:51

在linux ubuntu 测试过 可以用 赞赞!!!!!!

chinaunix网友2008-10-12 16:12:13

这是win 下的吧。

chinaunix网友2008-10-12 16:12:09

这是win 下的吧。