Checking available input on stdin

L

Lionel B

I know this has probably come up frequently, but couldn't find a satisfactory reference... I have some code which needs
to read from stdin but must not block waiting for input if there is no input pending on stdin. I have some code which
does the job (at least on my system... I wonder about the portability, though) but it's an ugly C hack; in particular I
am not happy about mixing C and C++ style I/O.

Simplified version:

--- BEGIN CODE: test.cpp ---

#include <cstdlib>
#include <iostream>
#include <sstream>

bool inavail(FILE* stream)
{
long int nchars;
if (fseek(stream,0,SEEK_END)!=0) return false;
if ((nchars=ftell(stream))<0) return false;
if (fseek(stream,0,SEEK_SET)!=0) return false;
return (nchars>0);
}

using namespace std;

int main()
{
ostringstream oss;
if (inavail(stdin)) oss << cin.rdbuf();

cout << '[' << oss.str() << ']';

return EXIT_SUCCESS;
}

--- END CODE ---


--- test.txt ---
foo
bar
-------------------

"Correct" results:

$ test < test.txt <RET>
[foo
bar]

$ test <RET>
[]

(no user intervention required; if the call to inavail() is omitted, then the second run waits for user input and EOF)

I guess I would be happy with a C++ equivalent of my inavail() function... the name is a giveaway: couldn't seem to get
anything useful out of streambuf::in_avail().

Any hints much appreciated,
 
D

David Harmon

On Fri, 22 Apr 2005 11:21:50 +0100 in comp.lang.c++, "Lionel B"
I know this has probably come up frequently, but
couldn't find a satisfactory reference...

That is because there is no satisfactory answer.
 
L

Lionel B

David said:
On Fri, 22 Apr 2005 11:21:50 +0100 in comp.lang.c++, "Lionel B"



That is because there is no satisfactory answer.

Possibly not... nevertheless I would be happy to replicate the
functionality of my (essentially C) inavail() function in a more C++
style - perhaps using streambuf. On the grounds of "Anything You Can Do
In C You Can Do In C++ (tm)" this ought to be possible...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top