我的目標是有一個程式可以從 C 中的檔案重定向中獲取用戶輸入。
$ ./hello < input.txt
但是當沒有重定向或引數時,程式將輸出一條訊息:
$ ./hello
There is nothing to read!
由于檔案重定向直接進入標準輸入,我使用 scanf 來讀取檔案的內容。但是,當我在沒有重定向的情況下啟動程式時scanf會等待輸入,而我的目標是僅從命令列上的重定向中獲取它,如果它沒有輸出訊息
uj5u.com熱心網友回復:
直到不可移植地檢查 stdin 是否是 tty,shell 無法判斷輸入來自哪里,它只能判斷它是否已經存在。你沒有說你在哪個平臺上,我假設你真正想要的只是/為了不阻止讀取/ - 你可以通過stdin以非阻塞方式輪詢來實作這一點:
#include <sys/select.h>
#include <stdio.h>
#include <unistd.h>
int poll_stdin() {
struct timeval tv;
fd_set fds;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
select(STDIN_FILENO 1, &fds, NULL, NULL, &tv);
return FD_ISSET(STDIN_FILENO, &fds);
}
size_t read_stdin(char *buf, size_t max) {
size_t n = 0;
while ((n < max) && (poll_stdin())) {
read(STDIN_FILENO, &buf[n ], 1);
}
if (n < max-1) buf[n] = '\0';
return n;
}
int main(int argc, char *argv[]) {
char buf[255];
size_t len;
buf[255] = '\0';
len = read_stdin(buf, 255);
if (len == 0) printf("No input!\n");
else printf(">%s\n", buf);
return 0;
}
輸出:
dtrombley@squall:~$ echo 'Hello, world!' > hello.txt
dtrombley@squall:~$ ./main
No input!
dtrombley@squall:~$ ./main < hello.txt
>Hello, world!
uj5u.com熱心網友回復:
使用 isatty()
這正是它的用途。
請注意,并非所有系統都提供健全的 isatty(),但任何聲稱符合 POSIX 的 *nixen 都可以正常作業。這是我當前的 *nixen 首選代碼(適用于 C):
#include <stdbool.h>
#include <unistd.h>
bool my_isatty( int id )
{
return (0 <= id) and (id <= 2) and isatty( id );
}
Windows 上有各種各樣的問題,特別是如果您使用 MSYS2 shell(它使用管道實作命令視窗,LOL,因此您必須使用一些低級作業系統的東西來檢查)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416396.html
標籤:
