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

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

问题描述

我有一个聊天客户端,需要在原终端输入模式,但我不知道在这种模式下处理输入。我需要知道两件事情:

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:


  • 如何读取字符逐个字符的输入和显示呢?我必须有某种形式的读循环,在一个缓冲时间,并将其存储读取一个字符?

  • 如果我想我的服务器来处理新的行输入的投入,我必须扫描每一个字符,因为它涉及到我的缓冲区,并寻找 \\ n <? / LI>
  • 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 \n?

另外,一个例子字符逐个字符阅读循环对刷新\\ n 会很高兴地看到。谢谢!

Also, an example character-by-character read loop that flushes on \n 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

编辑:这是一个最小的readline例如:

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.c的-lreadline -lncurses。

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

如果您不能使用输入行,函数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天全站免登陆