使终端输入在一定数量的字符后发送 [英] Making terminal input send after a certain number of characters

查看:68
本文介绍了使终端输入在一定数量的字符后发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C创建Linux终端程序.

I am creating a Linux terminal program using C.

我正在尝试使两位数字代码指向数组位置. 我不想在每两位输入后都按回车键,我只想在输入字符后直接通过scanf将输入发送到我的缓冲区变量.

I am trying to make a two digit code address a array location. I don't want to have to hit enter after every two digit input, I want the input to just be sent to my buffer variable through scanf directly after to characters are entered.

我没有代码示例,因为我不知道该如何处理.

I do not have a code sample, as i have no idea how to approach this.

感谢您的帮助!

推荐答案

您有两个选择,它们以几乎相同的方式解决相同的问题.第一种是在运行程序时使用stdbuf.调用是:

You've got two options, which solve the same problem in nearly the same way. The first is to use stdbuf when you run your program; the invocation is:

 stdbuf -i0 ./a.out

使用此功能可防止stdin被行缓冲,并允许您使用fread()或类似命令在发生输入时进行检索.

Using that prevents stdin from being line-buffered, and will let you use fread() or similar commands to retrieve input as it happens.

另一种方法是将终端置于 raw 模式. 此处.但缺点是不再处理控制字符.在您的程序中,您

The other is to put the terminal in raw mode. It's well-described here. But the downside is that control characters are no longer dealt with. In your program, you

#include <termios.h> 

main(){
    struct termios trm;

    tcgetattr(STDIN_FILENO, &trm); /* get the current settings */
    trm.c_cc[VMIN] = 1;     /* return after 1 byte read; you might make this a 2*/
    trm.c_cc[VTIME] = 0;    /* block forever until 1 byte is read */
    tcsetattr(STDIN_FILENO, TCSANOW, &trm); 
}

这篇关于使终端输入在一定数量的字符后发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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