如何让输入字符不回显(不使用curses库)

天蛾糊 2009-10-29 01:01:12
我在做密码输入的程序,用curses库已经实现了,但我觉得不方便,想请教各位高手来指点,谢谢
比如输入一个字符显示一个*直到'\n'为止
...全文
98 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
winter_sui 2009-10-29
  • 打赏
  • 举报
回复
网上搜索的:
#include <stdio.h>

#ifndef _WIN32 //Linux platform
#include <termio.h>
#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 <conio.h>
#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;
}

23,217

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧