原始终端模式 - 如何输入? [英] raw terminal mode - how to take in input?

查看:25
本文介绍了原始终端模式 - 如何输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以原始终端模式接收输入的聊天客户端,但我不知道如何在这种模式下处理输入.我需要知道两件事:

I have a chat client that takes in input in raw terminal mode, but I don't know about handling input in this mode. I need to know 2 things:

  • 如何逐个字符读取输入并显示?我是否必须有某种读取循环,一次读取一个字符并将其存储在缓冲区中?
  • 如果我希望我的服务器处理新行条目上的输入,我是否必须在每个字符进入我的缓冲区时对其进行扫描并查找 ?
  • How can I read the input in character-by-character and display it? Do I have to have some sort of a read loop that reads one character at a time and stores it in a buffer?
  • If I want my server to process the input on new line entry, do I have to scan each character as it comes into my buffer and look for ?

此外,一个在 上刷新的逐字符读取循环示例非常值得一看.谢谢!

Also, an example character-by-character read loop that flushes on would be really great to see. Thanks!

推荐答案

我推荐 GNU readline 库 为此.它负责获取输入行的繁琐工作,并允许用户使用退格、向左和向右箭头等编辑他的行,并使用向上箭头调用旧命令,甚至使用 ^R 搜索旧命令,等等.Readline 安装在典型的类 Unix 发行版中,例如 linux,但如果您没有它,您可以找到它 这里

I recommend the GNU readline library for this. It takes care of the tedious work of getting lines of input, and allows the user to edit his line with backspace, left and right arrows, etc, and to recall older command using the up arrow and even search for older command using ^R, etc. Readline comes installed with typical unix-like distributions like linux, but if you don't have it, you can find it here

这是一个最小的阅读示例:

Here is a minimal readline example:

#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>

int main(int argc, char ** argv)
{
    while(1)
    {
        char * line = readline("> ");
        if(!line) break;
        if(*line) add_history(line);
        /* Do something with the line here */
    }
}

使用 gcc -o test test.c -lreadline -lncurses 编译.

Compile with gcc -o test test.c -lreadline -lncurses.

如果您不能使用 readline,则可以使用 getline:

If you can't use readline, getline is an alternative:

#include <stdio.h>
int main()
{
    char * line = NULL;
    size_t len;
    while(getline(&line, &len, stdin) >= 0)
       printf("I got: %s", line);
}

如果连 getline 都不能接受,你可以使用 fgets.它不会动态分配合适大小的缓冲区,因此会截断太长的行.但至少它是标准的 C:

If even getline is unacceptable, you can use fgets. It will not dynamically allocate a buffer of suitable size, so too long lines will be truncated. But at least it is standard C:

#include <stdio.h>
int main()
{
    char buf[1000];
    while(fgets(buf, sizeof(buf), stdin)
        printf("I got: %s, line);      
}

这篇关于原始终端模式 - 如何输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆