Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
874 views
in Technique[技术] by (71.8m points)

testing - Test if stdin has input for C++ (windows and/or linux)

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.

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.

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;
}

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

Testing:

$ ./stdin
No
$ echo "foo" | ./stdin
Yep

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...