問題描述
我基本上想測(cè)試 stdin 是否有輸入(就像你回聲和管道輸入一樣).我找到了有效的解決方案,但它們很丑陋,我喜歡我的解決方案干凈.
I basically want to test if stdin has input (like if you echo and pipe it). I have found solutions that work, but they are ugly, and I like my solutions to be clean.
在 linux 上我使用這個(gè):
On linux I use this:
bool StdinOpen() {
FILE* handle = popen("test -p /dev/stdin", "r");
return pclose(handle) == 0;
}
我知道我應(yīng)該添加更多的錯(cuò)誤處理,但這不是重點(diǎn).
I know that I should add more error handling, but it's besides the point.
在 Windows 上我使用這個(gè):
On windows I use this:
bool StdinOpen() {
static HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
DWORD bytes_left;
PeekNamedPipe(handle, NULL, 0, NULL, &bytes_left, NULL);
return bytes_left;
}
這對(duì) linux 來說很好,但我想知道我可以在不使用管道的情況下調(diào)用的等效 API 是什么(例如對(duì)于 test -f $file
,您執(zhí)行 fopen($文件,"r") != NULL
).我有一種暗示,我可以 open("/dev/stdin", "r")
并做同樣的事情,但我想知道最好的方法.
That is fine for linux, but I want to know what are the equivalent APIs that I can call without using a pipe (like for test -f $file
you do fopen($file, "r") != NULL
). I have an inkling that I could open("/dev/stdin", "r")
and do the same thing, but I want to know the best way to do it.
總結(jié):我想知道我可以用來代替 Linux 的 test -p/dev/stdin
的 API,如果你知道更好的解決方案窗戶.
Summary: I want to know the APIs I could use to substitute for test -p /dev/stdin
for linux, and, if you know a better solution for windows.
推薦答案
這是 POSIX (Linux) 的解決方案:我不確定 Windows 上的 poll() 等價(jià)物是什么.在 Unix 上,編號(hào)為 0 的文件描述符是標(biāo)準(zhǔn)輸入.
Here's a solution for POSIX (Linux): I'm not sure what's the equivalent of poll() on Windows. On Unix, The file descriptor with number 0 is the standard input.
#include <stdio.h>
#include <sys/poll.h>
int main(void)
{
struct pollfd fds;
int ret;
fds.fd = 0; /* this is STDIN */
fds.events = POLLIN;
ret = poll(&fds, 1, 0);
if(ret == 1)
printf("Yep
");
else if(ret == 0)
printf("No
");
else
printf("Error
");
return 0;
}
測(cè)試:
$ ./stdin
No
$ echo "foo" | ./stdin
Yep
這篇關(guān)于測(cè)試 stdin 是否有 C++ 輸入(windows 和/或 linux)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!