[英]Prevent control-D to be echoed in terminal
當我使用 readline function 並鍵入 control-D 告訴我的程序它到達 EOF 時,終端中回顯了^D
。
我想刪除它或用另一條消息替換它。
我嘗試了stty -echoctl
命令,但它不起作用。
我將 ZSH 與 Oh My Zsh 和 iTerm2 一起使用。
# include<stdio.h>
# include<string.h>
# include<stdlib.h>
# include<unistd.h>
# include<sys/types.h>
# include<sys/wait.h>
# include<readline/readline.h>
# include<readline/history.h>
int input(void)
{
char *buf;
buf = readline("Please write the argument:\n");
if (buf == NULL)
{
printf("Quitting the program\n");
exit(0);
}
return (0);
}
int main()
{
while (1)
{
if(!input())
continue;
}
return (0);
}
我不知道我現在可以嘗試什么,我檢查了很多 Stack Overflow 線程但沒有找到任何東西。
盡管看起來您使用的是 readline 庫,但實際上您使用的是構建在BSD libedit 庫之上的兼容層,這是 Mac OS 默認提供的。 所以你可以期待一些事情會有所不同。
不幸的是,libedit 沒有很好的文檔記錄。 似乎可以通過在您的主目錄中創建文件名.editrc
並插入以下行來修改 Ctrl-D 鍵的綁定:
bind ^D ed-end-of-file
這會將更改應用於所有使用libedit
庫的應用程序,這可能有點激烈。 要使其僅適用於您的程序,您可以插入以下行:
rl_readline_name = "progname";
在你的程序開始時,在你第一次調用readline
之前。 progname
更改為您想要用作程序標簽的任何內容。 然后您可以將editrc
命令更改為以下內容(對progname
使用相同的標簽):
progname:bind ^D ed-end-of-file
至少,這適用於 Ubuntu 系統。
另一種選擇是在您的 Mac 上安裝 GNU readline。 根據GNU readline 主頁:
MacOS X 用戶可以從MacPorts獲得 readline-8.0 的 MacOS X 包,從Fink獲得 readline-7.0,或者從Homebrew獲得 readline-8.0。
然后你必須確保你用 GNU readline 而不是 libedit shim 來構建你的程序。
這樣做也會使提示按其讀取的方式工作(即,提示包含一個換行符)。 不過,我不知道這是否是你想要的。
你需要做的基本上是有一個 function 讀取並手動打印每個字符,這樣你就可以攔截不應該打印的字符。 這是一個開始的想法:
int ch;
char buf[SIZE] = {0};
char *p = buf;
while(1) {
ch = getchar();
if(ch == EOF) {
p[1] = 0;
break;
}
putchar(ch);
*p++ = ch;
}
您可能希望以特殊方式處理退格鍵'\b'
。 就像遞減p
一樣,但要注意越界。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.