如何在没有回声的情况下读取字符
How to read char without echo
在 (*1) 中我们有示例如何在 haskell 中使用 getChar 时关闭回显。这个想法是我们可以使用 hSetEcho stdin False
.
关闭回声
我想在 Idris 中做同样的事情。我有办法吗?
(*1) Haskell read raw keyboard input
您可能想要使用 curses bindings.
如果这对您的使用来说太重了,您可以编写 C 代码来处理您的终端,并通过 FFI 接口使用该代码。例如,您可以像这样为 Linux 终端使用 termios.h
:
termops.c
:
#include "termops.h"
#include <termios.h>
void set_echo(int fd) {
struct termios term;
tcgetattr(0, &term);
term.c_lflag |= ECHO;
tcsetattr(fd, TCSAFLUSH, &term);
}
void unset_echo(int fd) {
struct termios term;
tcgetattr(0, &term);
term.c_lflag &= ~ECHO;
tcsetattr(fd, TCSAFLUSH, &term);
}
termops.h
:
void set_echo(int fd);
void unset_echo(int fd);
termops.idr
:
%include C "termops.h"
setEcho : IO ()
setEcho = foreign FFI_C "set_echo" (Int -> IO ()) 0
unsetEcho : IO ()
unsetEcho = foreign FFI_C "unset_echo" (Int -> IO ()) 0
getPasswd : IO String
getPasswd = do
c <- getChar
if c == '\n'
then pure ""
else do rek <- getPasswd
pure $ strCons c rek
main : IO ()
main = do
unsetEcho
passwd <- getPasswd
setEcho
printLn passwd
要编译和link C 库,然后使用idris termops.idr --cg-opt "termops.c"
。
在 (*1) 中我们有示例如何在 haskell 中使用 getChar 时关闭回显。这个想法是我们可以使用 hSetEcho stdin False
.
我想在 Idris 中做同样的事情。我有办法吗?
(*1) Haskell read raw keyboard input
您可能想要使用 curses bindings.
如果这对您的使用来说太重了,您可以编写 C 代码来处理您的终端,并通过 FFI 接口使用该代码。例如,您可以像这样为 Linux 终端使用 termios.h
:
termops.c
:
#include "termops.h"
#include <termios.h>
void set_echo(int fd) {
struct termios term;
tcgetattr(0, &term);
term.c_lflag |= ECHO;
tcsetattr(fd, TCSAFLUSH, &term);
}
void unset_echo(int fd) {
struct termios term;
tcgetattr(0, &term);
term.c_lflag &= ~ECHO;
tcsetattr(fd, TCSAFLUSH, &term);
}
termops.h
:
void set_echo(int fd);
void unset_echo(int fd);
termops.idr
:
%include C "termops.h"
setEcho : IO ()
setEcho = foreign FFI_C "set_echo" (Int -> IO ()) 0
unsetEcho : IO ()
unsetEcho = foreign FFI_C "unset_echo" (Int -> IO ()) 0
getPasswd : IO String
getPasswd = do
c <- getChar
if c == '\n'
then pure ""
else do rek <- getPasswd
pure $ strCons c rek
main : IO ()
main = do
unsetEcho
passwd <- getPasswd
setEcho
printLn passwd
要编译和link C 库,然后使用idris termops.idr --cg-opt "termops.c"
。