这是我的getLine() 函数的略微修改版本,用于来自用户的稳健输入。您可以查看原始 here 的详细信息,但此版本已被修改为使用 termios 内容,可以对输入进行一定程度的控制。
因为termios 的工作级别低于标准 C 输入,所以它也会影响到这一点。
首先,getLine() 函数所需的标头和返回值:
#include <termios.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
#define TERM_PROB 3
接下来,一个帮助函数将终端恢复到其原始状态,这使您可以轻松地从 getLine() 返回一个值,知道终端将保持其原始状态。
static int revertTerm (int fd, struct termios *ptio, int old, int rc) {
// Revert the terminal to its original state then return
// specified value.
ptio->c_cc[VKILL] = old;
tcsetattr (fd, TCSANOW, ptio);
close (fd);
return rc;
}
接下来是实际的getLine() 函数本身,它修改终端属性以使 ESC 成为终止字符,然后调用fgets() 以及所有额外的提示,检测缓冲区溢出,刷新输入到行尾等等。
作为此功能的一部分,在用户位于fgets() 内期间,修改后的终端行为处于活动状态,您可以使用 ESC 清除该行。
static int getLine (char *prmpt, char *buff, size_t sz) {
int old, fd, ch, extra;
struct termios tio;
// Modify teminal so ESC is KILL character.
fd = open ("/dev/tty", O_RDWR);
if (fd < 0)
return TERM_PROB;
tcgetattr (fd, &tio);
old = tio.c_cc[VKILL];
tio.c_cc[VKILL] = 0x1b;
tcsetattr (fd, TCSANOW, &tio);
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return revertTerm (fd, &tio, old, NO_INPUT);
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return revertTerm (fd, &tio, old, (extra == 1) ? TOO_LONG : OK);
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return revertTerm (fd, &tio, old, OK);
}
最后是一个测试程序,以便您检查它的行为。基本上,它允许您输入最多 20 个字符的行,然后将它们打印出来并带有状态(太长、没有输入等)。
如果在输入过程中的任何时候按ESC,它将终止该行并重新开始。
输入exit会导致程序退出。
// Test program for getLine().
int main (void) {
int rc, done = 0;
char buff[21];
while (!done) {
rc = getLine ("Enter string (ESC to clear, exit to stop)> ",
buff, sizeof(buff));
if (rc == NO_INPUT) {
// Extra NL since my system doesn't output that on EOF.
printf ("\nNo input\n");
} else if (rc == TOO_LONG) {
printf ("Input too long [%s]\n", buff);
} else {
done = (strcmp (buff, "exit") == 0);
if (!done)
printf ("OK [%s]\n", buff);
}
}
return 0;
}