0

我正在使用 execvp 的 Linux 上编写 C++ 函数。传递给此函数的唯一参数是一个 char*,它指示 exec 的参数。我需要将此 char* 转换为 char** 用于 execvp,并且我需要考虑引号,这是一个示例:

/path/to/program "argument one" argument two
  - results in -
/path/to/program
argument one
argument
two

有没有一些内置的方法可以做到这一点?如果没有,除了编写自己的解析器之外,我还能做一些更简单的事情吗?

4

1 回答 1

1
#include <string>
#include <vector>

std::vector<std::string> stringToArgv(std::string const& in)
{
    std::vector<std::string> out;

    std::string arg;

    char quoteChar = 0;

    for (std::string::const_iterator I = in.begin(), E = in.end(); I != E; ++I)
    {
        char ch = *I;

        // Quoting a single character using the backslash?
        if (quoteChar == '\\')
        {
            arg.push_back(ch);
            quoteChar = 0;
            continue;
        }

        // Currently quoting using ' or " ?
        if (quoteChar && ch != quoteChar)
        {
            arg.push_back(ch);
            continue;
        }

        switch (ch)
        {
        case '\'': // Toggle quoting
        case '\"': // Toggle weak quoting
        case '\\': // Toggle single character quoting...
            quoteChar = quoteChar ? 0 : ch;
            break;

        case ' ':
        case '\t':
        case '\n':
            // Arguments are separated by whitespace
            if (!arg.empty())
            {
                out.push_back(arg);
                arg.clear();
            }
            break;

        default:
            arg.push_back(ch);
            break;
        }
    }

    // Append the last argument - if any
    if (!arg.empty())
    {
        out.push_back(arg);
    }

    return out;
}
于 2013-08-11T20:33:10.690 回答