r/C_Programming • • 11d ago

Question C input that doesn't convert arrow keys to raw escape sequences

When someone was testing my project in C, they pointed out that when they press arrow keys in input it translates them into weird data (eg. ^[[A for up). Is there input in C without ncurses or other libraries that can work in this scenario without causing these issues?

13 Upvotes

21 comments sorted by

38

u/deaddodo 11d ago

Arrow keys are not standard characters, they are control sequences (along with many of the non-character keys on your keyboard). If you want to handle them, you have to use OS-specific functions (termios on Linux, conio's getch on Windows, etc), manually process the sequence (readline+parsing), or use a third-party library that abstracts that out for you (ncurses, as you mentioned).

5

u/Treechcer 11d ago

Okay, thank you. I'll look into it.

5

u/Interesting_Debate57 11d ago

When in doubt about what is or is not a character, just type in a unix terminal:

man ascii

and it'll show you exactly everything that is a character, along with very specialized escape code meanings, everything in hexadecimal, all of the goodies you can want.

It's not mentioned in the manpage, but that's only the bottom seven bits. Microsoft has its own interpretation of that top bit, depending upon file format.

3

u/Treechcer 10d ago

You can do man ascii??? Thank you man

1

u/agmatine 9d ago

You can even do man man! Or man man man (q) (enter) (q) for more man. You can put as many man as you like!

-2

u/dack42 10d ago

There are loads of characters that aren't ASCII. That's why Unicode exists.

1

u/Interesting_Debate57 10d ago

Yes, but OP clearly doesn't have his character encoding set to Unicode.

3

u/[deleted] 11d ago

Standard C input functions are not supposed to handle arrow keys, they are just sending codes. Either use rlwrap on your program, or change your program to use readline.

2

u/Treechcer 11d ago

Read line does that automatically?

4

u/[deleted] 11d ago

2

u/ignorantpisswalker 10d ago

Is your terminal in raw input mode?

1

u/Treechcer 10d ago

I don't know?

2

u/ignorantpisswalker 10d ago

https://stackoverflow.com/questions/19400194/linux-keyboard-scancode-issues-for-example-up-arrow-gives-a

Read that answer. Basically if you want to read those keys, the terminal needs to be in a special mode.

2

u/Educational-Paper-75 10d ago

In raw input mode you can read escape sequences one character at a time.

1

u/chibuku_chauya 10d ago

Others have mentioned GNU readline. It’s fine but if you don’t care for its size, you can use editline.

1

u/sciencekm 10d ago

This should print the characters that maps to keys.

#include <stdio.h>
#if _WIN32
  #include <windows.h>
  #define SCM SetConsoleMode
  #define RCA ReadConsoleA
  #define GCM(h,s,d) GetConsoleMode(h = GetStdHandle((DWORD)s), &d)
  #define _kbhit() (WaitForSingleObject(hI, 0) == WAIT_OBJECT_0)
  static HANDLE hI, hE;
  static DWORD IM, EM, CN[1];
  static char kb(void) { CHAR c; return RCA(hI, &c, 1, CN, 0), c; }
  static int setscr(int m) { return m ? (SCM(hI, IM), SCM(hE, EM)) :
    (GCM(hI, -10, IM), GCM(hE, -12, EM), SCM(hI, 512), SCM(hE, 5));}
#else
  #include <stdlib.h>
  #include <unistd.h>
  #include <termios.h>
  static struct termios tiold, tinew;
  static int setscr (int m) { return m ? tcsetattr(0, TCSANOW, &tiold) :
    (tcgetattr(0, &tiold), tinew = tiold,
    tinew.c_cc[VMIN ] = 1, tinew.c_cc[VTIME] = 0,
    tinew.c_lflag &= (~ICANON & ~ECHO & ~ISIG),
    tinew.c_iflag &= (~IXON), tcsetattr(0, TCSANOW, &tinew)); }
  static char kb(void) { char c; return read(0, &c, 1) ? c : 0; }
  static int _kbhit(void) { struct timeval t = { 0 }; fd_set s[1];
    FD_ZERO(s); FD_SET(0, s); return select(0+1, s, 0, 0, &t) > 0; }
#endif
int main(void) {
  int c = 0;
  for (setscr(0); c != 10 && c != 13; puts(""))
    do {
      c = kb();
      if (c <= 26) printf("^%c ", 'A' + c - 1);
      else if (c <= ' ' || c >= 127) printf("\\%o ", c);
      else printf("%c ", c);
    } while (_kbhit());
  return setscr(1);
}

1

u/yel50 10d ago

that's a Unix convention. Unix clients were assumed to be running on a different machine than the server, so the server didn't have access to raw keyboard events. they came up with the sequences as a way to send control characters across a network.

on modern Unix systems, like Linux, reading the keyboard directly requires root access. that's why GUI programs get raw key events but terminal programs don't. the GUI server, i.e. X windows or Wayland, runs as root, reads the keyboard, and forwards the event to the right application.

so, you either have to do the Unix sequence stuff, run as a GUI instead of command line, require root privileges and read from the keyboard device, or use windows instead of Linux. windows doesn't have the same restrictions and command line apps can still get raw key events.

2

u/ElHeim 9d ago

Uh... Or you can switch from canonical to non-canonical mode (cooked/raw, whatever you want to call them). No need to be root.

1

u/agmatine 9d ago edited 9d ago

You mean the stty settings? For example, man -K 'same as raw'.

2

u/ElHeim 9d ago

I meant the C API to set the terminal attributes (man termios), but close enough.

1

u/0jdd1 10d ago

My first UNIX™ was v6. User-typed characters were buffered until the user hit a new-line equivalent or the ^D character, at which point the next read(1) typically returned the characters typed so far. That’s in cooked mode; raw mode did not buffer characters like this.