如果想知道標準輸出是否被重定向了,只需要檢查底層的文件描述符是否關聯到了一個終端即可。系統調用isatty就是用來完成這個任務的。 你只需要將有效的文件描述符傳遞給它,它就能判斷是否連接到了一個終端。 linux提供了一個特殊的設備/dev/tty來解決對終端的讀寫問題,這個設備始終指向當前終端或當前登錄的會話,由于linux把一切事物都當作 文件來看,所以,我們可以像操作一般的文件來操作對/dev/tty的讀寫。
#include <stdio.h> #include <unistd.h> #include <stdlib.h> char *menu[] = { "a - add new record", "d - delete record", "q - quit", NULL, }; int getchoice(char *greet, char *choices[], FILE *in, FILE *out); int main() { int choice = 0; FILE *input; FILE *output; if (!isatty(fileno(stdout))) { f重定向標準輸出到文件,此時stdout不是終端,所以輸出如下:gcc putty.c ./a.out >file You are not a terminal,OK.
正常執行如下:
./a.out You have chosen: a Choice: Please select an action a - add new record d - delete record q - quit d You have chosen: d Choice: Please select an action a - add new record d - delete record q - quit c Incorrect choice, select again Choice: Please select an action a - add new record d - delete record q - quit
新聞熱點
疑難解答