linux下退格键的小研究(续)

来源:互联网 发布:focusky破解补丁mac 编辑:程序博客网 时间:2024/06/05 18:39

    上次出现的backspace在输入的时候显示^H的问题,请教了一下组里的老司机,老司机说,这是回显的问题,要把那个echo什么的修改一下,顺着这条思路,查了点资料,上面一篇博客就是其中之一。

    废话少说,直接放码:

    

#include <stdio.h>#include <unistd.h>#include <termios.h>#define LEN 30struct termios oldt, newt;void mode_off(void);void mode_restore(void);void get_username(char * string, int len){char ch;int i=0;mode_off();puts("\nusername:\n");while((ch=getchar())=='\n');while(ch!='\n' && i<len-2 && i>=0 ){if(ch=='\b'){string[--i]='\0';putchar('\b');putchar(' ');putchar('\b');}    else    {string[i++]=ch;    putchar(ch);}        ch=getchar();}putchar('\n');string[i]='\0';mode_restore();}void get_password(char * string, int len){char ch;int i=0;mode_off();puts("\npassword:\n");while((ch=getchar())=='\n');while(ch!='\n' && i<len-2 && i>=0 ){if(ch=='\b'){string[--i]='\0';putchar('\b');putchar(' ');putchar('\b');}    else    {string[i++]=ch;    putchar('*');}        ch=getchar();}putchar('\n');string[i]='\0';mode_restore();}void mode_off(void)   //off echo{newt=oldt;newt.c_lflag &= ~(ECHO | ICANON);tcsetattr(STDIN_FILENO, TCSANOW, &newt);}void mode_restore(void)   //restore echo{tcsetattr(STDIN_FILENO, TCSANOW, &oldt);}

    mode_off是关掉回显,mode_restore是恢复原来的模式,get_username是输入用户名,get_password是输入密码。关于结构体struct termios、tcgetattr()和tcsetattr()见上一篇文章,或者自己查资料。    

    关掉回显后,读一个显示一个,如果读到backspace,光标往回退一个,输个空格,覆盖原来的字符,再退一格,往前进一步。输密码的时候,则是输一个字符,显示一个*。

    至此,backspace的问题基本解决。

原创粉丝点击