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,
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,