The function _getch() behaves unexpectedly in git-bash terminal

94 Views Asked by At

I have been trying to figure out how it is possible to change the terminal's mode from "cooked" to "raw" using C and in a Git Bash terminal.

I have tried to execute the program with winpty and that makes that certain part of the program function as expected. However, it messes up the other parts, like clearing the screen with the control sequence \x1b[2J, and vice versa. Clearing the screen works perfectly when I am NOT executing the program with winpty.

I have also tried using system("clear") and system("cls") but with no luck. I have also tried to set the mode using the function _setmode(_fileno(stdin), _O_BINARY) but no such function seems to be working with Git Bash and more specifically MinTTY.

When I am using getch() nothing simply happens and I have to use CTRL+C to exit the program. However, it should exit the program when I press the 'i' character.

The code looks like this:

#include <windows.h>
#include <conio.h>
#include <stdio.h>

void clear_screen() {
    printf("\\033\[2J");
    printf("\\033\[1;1H");
    fflush(stdout);
}

int main() {
#ifdef _WIN32
    clear_screen();
    while (1) {
        char c = _getch();
        if (c == 'i') {
            exit(0);
        }
    }
#endif

#ifdef linux
#endif
}
0

There are 0 best solutions below