programing

Linux에서 getch() & getche()에 해당하는 것은 무엇입니까?

prostudy 2022. 6. 18. 09:19
반응형

Linux에서 getch() & getche()에 해당하는 것은 무엇입니까?

conio에 해당하는 헤더 파일을 찾을 수 없습니다.h(Linux의 경우).

에 대한 옵션이 있습니까?getch()&getche()Linux에서 작동합니까?

스위치 케이스 베이스 메뉴를 만들고 싶다.키 1개를 누르는 것만으로, 조작을 진행할 수 있다.사용자가 선택을 누른 후 ENTER를 누르도록 하고 싶지 않습니다.

#include <termios.h>
#include <stdio.h>

static struct termios old, current;

/* Initialize new terminal i/o settings */
void initTermios(int echo) 
{
  tcgetattr(0, &old); /* grab old terminal i/o settings */
  current = old; /* make new settings same as old settings */
  current.c_lflag &= ~ICANON; /* disable buffered i/o */
  if (echo) {
      current.c_lflag |= ECHO; /* set echo mode */
  } else {
      current.c_lflag &= ~ECHO; /* set no echo mode */
  }
  tcsetattr(0, TCSANOW, &current); /* use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void) 
{
  tcsetattr(0, TCSANOW, &old);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo) 
{
  char ch;
  initTermios(echo);
  ch = getchar();
  resetTermios();
  return ch;
}

/* Read 1 character without echo */
char getch(void) 
{
  return getch_(0);
}

/* Read 1 character with echo */
char getche(void) 
{
  return getch_(1);
}

/* Let's test it out */
int main(void) {
  char c;
  printf("(getche example) please type a letter: ");
  c = getche();
  printf("\nYou typed: %c\n", c);
  printf("(getch example) please type a letter...");
  c = getch();
  printf("\nYou typed: %c\n", c);
  return 0;
}

출력:

(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g
#include <unistd.h>
#include <termios.h>

char getch(void)
{
    char buf = 0;
    struct termios old = {0};
    fflush(stdout);
    if(tcgetattr(0, &old) < 0)
        perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if(tcsetattr(0, TCSANOW, &old) < 0)
        perror("tcsetattr ICANON");
    if(read(0, &buf, 1) < 0)
        perror("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if(tcsetattr(0, TCSADRAIN, &old) < 0)
        perror("tcsetattr ~ICANON");
    printf("%c\n", buf);
    return buf;
 }

마지막 제거printf문자를 표시하지 않을 경우 선택합니다.

curses.h 또는 ncurses를 사용하는 것이 좋습니다.h 이들은 getch를 포함한 키보드 관리 루틴을 구현한다.getch 동작을 변경할 수 있는 옵션은 여러 가지가 있습니다(즉, 키를 누르기를 기다리거나 하지 않습니다).

ncurses 라이브러리에는 getch() 함수가 있습니다.ncurses-dev 패키지를 설치하면 얻을 수 있습니다.

를 사용할 수 있습니다.curses.h다른 답변에서 언급한 바와 같이 라이브러리가 Linux에 있습니다.

Ubuntu에는 다음 방법으로 설치할 수 있습니다.

sudo apt-업데이트를 얻다

sudo apt-get install ncurses-dev

여기서부터 설치 부분은 제가 맡았습니다.

위와 같이getch()에 있습니다.ncurses도서관.ncurses를 초기화해야 합니다.예를 들어 getchar()는 이 키에 대해 위 화살표 키와 아래 화살표 키에 대해 동일한 값(27)을 반환합니다.

언급URL : https://stackoverflow.com/questions/7469139/what-is-the-equivalent-to-getch-getche-in-linux

반응형