The sorry state of the D stack?
Adam D. Ruppe
destructionator at gmail.com
Sat Oct 6 07:38:12 PDT 2012
On Saturday, 6 October 2012 at 12:52:36 UTC, bearophile wrote:
> I think the need for a Phobos portable way to read a char in is
> present.
I just slapped together a very quick Linux struct:
=====
version(Posix):
import core.sys.posix.termios;
import core.sys.posix.unistd;
import core.sys.posix.sys.types;
import core.sys.posix.sys.time;
import core.stdc.stdio;
enum ConsoleInputFlags {
raw = 0,
echo = 1
}
struct RealTimeConsoleInput {
@disable this();
@disable this(this);
private int fd;
private termios old;
this(ConsoleInputFlags flags) {
this.fd = 0; // stdin
tcgetattr(fd, &old);
auto n = old;
auto f = ICANON;
if(!(flags & ConsoleInputFlags.echo))
f |= ECHO;
n.c_lflag &= ~f;
tcsetattr(fd, TCSANOW, &n);
}
~this() {
tcsetattr(fd, TCSANOW, &old);
}
bool kbhit() {
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
fd_set fs;
FD_ZERO(&fs);
FD_SET(fd, &fs);
select(fd + 1, &fs, null, null, &tv);
return FD_ISSET(fd, &fs);
}
char getch() {
return cast(char) .fgetc(.stdin);
}
}
===
Usage:
void main() {
auto input = new
RealTimeConsoleInput(ConsoleInputFlags.raw);
while(true) {
if(input.kbhit()) { // is a key available?
auto c = input.getch(); // get it
if(c == 'q' || c == 'Q')
break;
printf("%c", c);
fflush(stdout);
}
usleep(10000);
}
}
IIRC it is very easy to do this on Windows as there's no need to
change the console mode.
More information about the Digitalmars-d
mailing list