[英]how to read stdin to end in qt?
我有一個qt-app,可以調用:
cat bla.bin | myapp
什么是在Win,Mac和Linux上讀取整個輸入(stdin)到QByteArray的最簡單方法?
我厭倦了幾件事,但似乎都沒有(在Windows上):
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QByteArray content;
//---Test 1: hangs forever, reads 0
while(!std::cin.eof()) {
char arr[1024];
int s = std::cin.readsome(arr,sizeof(arr));
content.append(arr,s);
}
//---Test 2: Runs into timeout
QFile in;
if(!in.open(stdin,QFile::ReadOnly|QFile::Unbuffered)) {
qDebug() << in.errorString();
}
while (in.waitForReadyRead(1000)) {
content+=in.readAll();
}
in.close();
return app.exec();
}
我有事件循環問題還是不應該沒有?
實際上從stdin
讀取的主要問題源於使用readsome
。 readsome
通常不用於從文件中讀取(包括stdin)。 Readsome
通常用於異步源上的二進制數據。 從技術上講, eof
並沒有設置readsome
。 在這方面, read
是不同的,因為它將相應地設置eof
。 有一個SO問題/答案在這里可能會感興趣。 如果你支持Linux和Windows並讀取stdin,你必須要知道在Windows上stdin
不是以二進制模式打開的( stdout
也不是)。 在Windows上,您必須在stdin
上使用_setmode
。 一種方法是使用#ifdef
使用Q_OS_WIN32
。 使用QFile無法解決此問題。
在您嘗試創建它的代碼中,您似乎對實際擁有事件循環感興趣。 您仍然可以在沒有事件循環的情況下使用QByteArray等QT對象。 在您的代碼中,您從stdin( cin
)讀取數據,然后執行return app.exec();
它將您的控制台應用程序置於循環中等待事件。 您沒有在app.exec();
之前向QT事件隊列添加任何事件app.exec();
所以你唯一能做的就是用control-c結束你的應用程序。 如果不需要事件循環那么這樣的代碼就足夠了:
#include <QCoreApplication>
#include <iostream>
#ifdef Q_OS_WIN32
#include <fcntl.h>
#include <io.h>
#endif
int main()
{
QByteArray content;
#ifdef Q_OS_WIN32
_setmode(_fileno(stdin), _O_BINARY);
#endif
while(!std::cin.eof()) {
char arr[1024];
std::cin.read(arr,sizeof(arr));
int s = std::cin.gcount();
content.append(arr,s);
}
}
注意我們如何使用QByteArray
但沒有QCoreApplication app(argc, argv);
並調用app.exec();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.