Guest User

Untitled

a guest
Jan 5th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //==================== main.cpp
  2. #include <QtCore/QCoreApplication>
  3.  
  4. #include "stdinstreamreader.h"
  5.  
  6. int main(int argc, char *argv[])
  7. {
  8.     QCoreApplication a(argc, argv);
  9.  
  10.     StdInStreamReader reader;
  11.  
  12.     return a.exec();
  13. }
  14.  
  15. //==================== stdinstreamreader.h
  16. #ifndef STDINSTREAMREADER_H
  17. #define STDINSTREAMREADER_H
  18.  
  19. #include <QObject>
  20. #include <QSocketNotifier>
  21.  
  22. class StdInStreamReader : public QObject
  23. {
  24.     Q_OBJECT
  25. public:
  26.     explicit StdInStreamReader(QObject *parent = 0);
  27.  
  28. signals:
  29.  
  30. public slots:
  31.     void receivedData(const int &socketId);
  32. };
  33.  
  34. #endif // STDINSTREAMREADER_H
  35.  
  36. //==================== stdinstreamreader.cpp
  37. #include "stdinstreamreader.h"
  38.  
  39. #include <QDebug>
  40. #include <QCoreApplication>
  41.  
  42. StdInStreamReader::StdInStreamReader(QObject *parent) :
  43.     QObject(parent)
  44. {
  45.     QSocketNotifier *notifier = new QSocketNotifier(fileno(stdin), QSocketNotifier::Read, this);
  46.     connect(notifier, SIGNAL(activated(int)), this, SLOT(receivedData(int)));
  47.     notifier->setEnabled(true);
  48. }
  49.  
  50. void StdInStreamReader::receivedData(const int &socketId)
  51. {
  52.     Q_UNUSED(socketId)
  53.  
  54.     QByteArray ba;
  55.     bool close = false;
  56.  
  57.     while (true) {
  58.         char c = getc(stdin);
  59.  
  60.         if (c == EOF) {
  61.             close = true;
  62.         }
  63.  
  64.         if (c == EOF || c == '\0' || c == '\n') {
  65.             break;
  66.         }
  67.         if (c)
  68.             ba.append(c);
  69.     }
  70.     qDebug() << "Received: " << QString::fromLocal8Bit(ba);
  71.  
  72.     if (QString::fromLocal8Bit(ba).startsWith("close") || close) {
  73.         QCoreApplication::exit(EXIT_SUCCESS);
  74.     }
  75. }
Add Comment
Please, Sign In to add comment