c - 如何在C中正确使用setvbuf?

标签 c io buffering

我想使用 setvbuf() 将输入流设置为无缓冲,但我真的不知道如何使用它。

我做了一些谷歌搜索,发现当您将流设置为无缓冲时,缓冲区和大小参数将被忽略,如 this article 所说。 .

这是我的代码:

#include "structures.h"
#include "functions.h"

char choice;
int option;

int main(void) {
    while(1) {
        puts("============================================Select an Option============================================");
        puts("1. Create Linked List");
        puts("2. Display items");
        puts("3. Add item to the beginning");
        puts("4. Add item to the end");
        puts("5. Add item in the middle");
        puts("6. Delete item from the beginning");
        puts("7. Delete item from the end");
        puts("8. Delete item from the middle");
        puts("9. Exit");
        printf(">>> ");

        setvbuf(stdin, _IONBF);
        choice = getchar();
        cleanStdin();
        option = choice - '0';

        //...
    }
}

文章说它们被忽略,但我仍然收到有关参数不足的错误,所以我不知道要在那里放什么。有人可以帮我吗?

最佳答案

使用参数:

setvbuf(stdin, NULL, _IONBF, 0);

但是,这不允许您在不按 Enter 的情况下从终端读取字符,这是一个终端问题,而不是缓冲问题,因为您需要一些东西否则。

您可以使用ncurses,这是建议的路线,但您也可以使用本文What is the equivalent to getch() & getche() in Linux?中接受的答案这使您能够做到这一点。

您可以在这里看到它的工作情况:https://replit.com/@anastaciu/ConcernedAncientMenu

关于c - 如何在C中正确使用setvbuf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67215247/

相关文章:

perl - “select((select(s),$|=1)[0])”在Perl中做什么?

javascript - 我可以从整个视频中接收一些数据并选择性地控制其余数据吗?

c++ - 现有的静态方法可以使用函数指针成为全局方法吗?

C++ 迭代,文件 i/o

Haskell 处理 [IO 字符串]

Mysql通过缓冲降低CPU使用率

c - posix 的线程优先级

c - 如果以 32 位编译,Ubuntu 上的 getpwnam 行为会有所不同

c++ - 快速三角函数仅使用 c++ 中的整数作为 arm 目标

io - swift 是否有写入字节流的协议(protocol)?