ciobuffering

How to properly use setvbuf in C?


I would like to set my input stream as unbuffered using setvbuf() but I don't really know how to use it.

I've done some googling and found that when you set a stream to unbuffered, the buffer and size parameters are ignored, as said by this article.

Here is my code:

#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';

        //...
    }
}

The article says they're ignored but I still get an error about not enough parameters, so I don't know what to put in there. Can someone help me please?


Solution

  • Use fake parameters:

    setvbuf(stdin, NULL, _IONBF, 0);
    

    This, though, will not allow you to read charaters from the terminal without pressing Enter, this a terminal problem, not a buffering one, for that you need something else.

    You can you use ncurses, which is the advised route, but you can also use the accepted answer in this post What is the equivalent to getch() & getche() in Linux? which allows you to do exactly that.

    You can see it working here: https://replit.com/@anastaciu/ConcernedAncientMenu