PDA

View Full Version : stdin reading



gmc
26th July 2012, 22:41
hi,

i'd like to read stdin like this:



QFile in;
in.open(stdin, QIODevice::ReadOnly);
QString line = in.readLine();


But if no data is written to stdin (by another process) then it hangs...
How can i determine if there is anything to read or not?
in.atEnd() does not work, in.bytesAvailable() does not work... they always return 0, even if the other process has written data to stdin.
So before calling in.readLine() i would like to know if there is data available, because i want QString line to be empty, if stdin is empty.

Thanks!
Oh and it is win32, i've read QSocketNotifier can be used in linux to notify if data has been written to stdin...

amleto
26th July 2012, 23:48
why not use cin and `operator >> ` ?

for the socket trick you have to make sure the buffer is not used. I didn't know that trick was linux only.

you can try this,


QTextStream qtin(stdin);
QString line = qtin.readLine(); // This is how you read the entire line

QString word;
qtin >> word; // This is how you read a word (separated by space) at a time.

as suggested here http://stackoverflow.com/questions/2321880/is-it-possible-to-use-cin-and-qt

gmc
26th July 2012, 23:58
Thanks.
i've already tried that, still waits until data is written to stdin :(

amleto
27th July 2012, 00:03
in that case get the rdbuf from cin.

gmc
27th July 2012, 00:12
still waits... could you write some more details how to do that?

i've tried this too:



std::string line;
std::getline( std::cin, line );


But still hangs and waits for data... it's so annoying. Why can't just read an empty line if nothing is there? or at least .bytesAvailable could be non-zero when i write to the stdin so i could check before reading..

amleto
27th July 2012, 19:33
I said try and use rdbuf. I don't see you use rdbuf anywhere. It is a member of cin

http://www.cplusplus.com/reference/iostream/ios/rdbuf/


I have just tried it, and it does not block.

Corvin7
28th May 2013, 16:25
to
amleto

Could you show an example how you used rdbuf to read from stdin and not block main event loop, please? Thanks in advance