测试stdin是否有输入的C ++(windows和/或linux) [英] Test if stdin has input for C++ (windows and/or linux)
问题描述
我基本上想测试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我使用这:
On linux I use this:
bool StdinOpen() {
FILE* handle = popen("test -p /dev/stdin", "r");
return pclose(handle) == 0;
}
我知道我应该添加更多的错误处理,但它除了点。
I know that I should add more error handling, but it's besides the point.
在Windows上,我使用这个:
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;
}
这对linux很好,但我想知道什么是等效的API我可以调用而不使用管道(像 test -f $ file
你做 fopen($ file,r)! / code>)。我有一个花样,我可以
打开(/ 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.
摘要:我想知道我可以用来代替 test -p / dev / stdin
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()。在Unix上,具有编号0的文件描述符是标准输入。
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\n");
else if(ret == 0)
printf("No\n");
else
printf("Error\n");
return 0;
}
测试:
$ ./stdin
No
$ echo "foo" | ./stdin
Yep
这篇关于测试stdin是否有输入的C ++(windows和/或linux)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!