简体   繁体   中英

Passing argument string which contains spaces and quotes

Using QProcess::startDetached , I need to pass a dynamic argument list which is coming from another process to the starting process.

const QString & prog, const QStringList & args, const QString & workingDirectory ...)

Note that arguments that contain spaces are not passed to the process as separate arguments.

...

Windows: Arguments that contain spaces are wrapped in quotes. The started process will run as a regular standalone process.

I have a string which contains below text, It comes from an external program without any control on it:

-c "resume" -c "print 'Hi!'" -c "print 'Hello World'"

I need to pass above string to QProcess::startDetached so that the starting program catches it as same as above string.

Do I have to parse the string and build a string-list? Or anyone has a better solution?

You don't have to use a QStringList at all for the arguments, as there is this overloaded function: -

bool QProcess::startDetached(const QString & program)

Which, as the documentation states: -

Starts the program program in a new process. program is a single string of text containing both the program name and its arguments . The arguments are separated by one or more spaces.

The program string can also contain quotes, to ensure that arguments containing spaces are correctly supplied to the new process.

You may need to replace " with \\", but you can do that from a QString

You can use parseCombinedArgString (from Qt's source code) to parse:

QStringList parseCombinedArgString(const QString &program)
{
    QStringList args;
    QString tmp;
    int quoteCount = 0;
    bool inQuote = false;
    // handle quoting. tokens can be surrounded by double quotes
    // "hello world". three consecutive double quotes represent
    // the quote character itself.
    for (int i = 0; i < program.size(); ++i)
    {
        if (program.at(i) == QLatin1Char('"'))
        {
            ++quoteCount;
            if (quoteCount == 3)
            {
                // third consecutive quote
                quoteCount = 0;
                tmp += program.at(i);
            }
            continue;
        }
        if (quoteCount)
        {
            if (quoteCount == 1)
                inQuote = !inQuote;
            quoteCount = 0;
        }
        if (!inQuote && program.at(i).isSpace())
        {
            if (!tmp.isEmpty())
            {
                args += tmp;
                tmp.clear();
            }
        }
        else
        {
            tmp += program.at(i);
        }
    }
    if (!tmp.isEmpty())
        args += tmp;
    return args;
}

是的,您必须“解析”字符串,将其拆分到正确的位置,然后将每个子字符串输入到传递给函数的QStringList对象中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM