I want to pass an argument containing asterisk to QProcess. The code listed below can reproduce my problem:
#include <QDebug>
#include <QProcess>
int main(int argc, char * argv[])
{
QStringList arguments;
arguments << "-l" << "*.cpp";
QProcess ps;
ps.start("ls", arguments);
ps.waitForFinished();
qDebug() << ps.readAll();
}
I can't get ls -l *.cpp
run as in a shell. What is the right way to make wildcard characters work for QProcess? I'm using Qt 5.15.2 coming with Debian stable.
CodePudding user response:
When you run ls -l *.cpp
, the expansion of *
to a list of filenames is performed by your shell.
In this case, ls
already receives a list of filenames.
In the case of QProcess
, the process is directly executed without a shell. So there is no party involved that performs the expansion (called "globbing").
In your case, I would use QDir::entryList()
to obtain the list of files and then pass the result as arguments.
Untested example code:
#include <QDebug>
#include <QProcess>
#include <QDir>
int main(int argc, char * argv[])
{
QStringList arguments = {"-l"};
QDir directory("."); // same as QDir()
QStringList filters = {"*.cpp"};
arguments << directory.entryList(filters);
QProcess ps;
ps.start("ls", arguments);
ps.waitForFinished();
qDebug() << ps.readAll();
}