【问题标题】:Making terminal input send after a certain number of characters使终端输入在一定数量的字符后发送
【发布时间】:2012-02-29 10:59:51
【问题描述】:

我正在使用 C 创建一个 Linux 终端程序。

我正在尝试将两位代码地址设为数组位置。 我不想在每输入两位数后都按回车键,我希望在输入字符后直接通过 scanf 将输入发送到我的缓冲区变量。

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

感谢您的帮助!

【问题讨论】:

    标签: c linux input terminal


    【解决方案1】:

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

     stdbuf -i0 ./a.out
    

    使用它可以防止stdin 被行缓冲,并允许您使用fread() 或类似的命令在发生输入时检索输入。

    另一种是将终端置于raw模式。很好地描述了here。但缺点是不再处理控制字符。在你的程序中,你

    #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); 
    }
    

    【讨论】:

    • 谢谢。我最终使用了 curses.h 中的 cbreak,因为你使用原始模式的原因。
    猜你喜欢
    • 2016-10-29
    • 1970-01-01
    • 2016-03-19
    • 2022-11-26
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2019-02-17
    相关资源
    最近更新 更多