gpt4 book ai didi

c++ - PathGetArgs/PathRemoveArgs 与 CommandLineToArgvW - 有区别吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:26 25 4
gpt4 key购买 nike

我正在研究一些路径解析 C++ 代码,为此我一直在试验许多 Windows API。 PathGetArgs/PathRemoveArgs 和稍微按摩过的 CommandLineToArgvW 之间有区别吗?

换句话说,除了长度/清洁之外,是这样的:

std::wstring StripFileArguments(std::wstring filePath)
{
WCHAR tempPath[MAX_PATH];

wcscpy(tempPath, filePath.c_str());
PathRemoveArgs(tempPath);

return tempPath;
}

不同于此:

std::wstring StripFileArguments(std::wstring filePath)
{
LPWSTR* argList;
int argCount;
std::wstring tempPath;

argList = CommandLineToArgvW(filePath.c_str(), &argCount);

if (argCount > 0)
{
tempPath = argList[0]; //ignore any elements after the first because those are args, not the base app

LocalFree(argList);

return tempPath;
}

return filePath;
}

是这个

std::wstring GetFileArguments(std::wstring filePath)
{
WCHAR tempArgs[MAX_PATH];

wcscpy(tempArgs, filePath.c_str());
wcscpy(tempArgs, PathGetArgs(tempArgs));

return tempArgs;
}

不同于

std::wstring GetFileArguments(std::wstring filePath)
{
LPWSTR* argList;
int argCount;
std::wstring tempArgs;

argList = CommandLineToArgvW(filePath.c_str(), &argCount);

for (int counter = 1; counter < argCount; counter++) //ignore the first element (counter = 0) because that's the base app, not args
{
tempArgs = tempArgs + TEXT(" ") + argList[counter];
}

LocalFree(argList);

return tempArgs;
}

?在我看来,PathGetArgs/PathRemoveArgs 只是提供了一个更清晰、更简单的 CommandLineToArgvW 解析的特例实现,但我想知道是否存在 API 行为不同的极端情况。

最佳答案

函数相似但不完全相同 - 主要与如何处理引用字符串有关。

PathGetArgs 返回指向输入字符串中第一个空格后的第一个字符的指针。如果在第一个空格之前遇到引号字符,则在函数再次开始查找空格之前需要另一个引号。如果未找到空格,则该函数返回指向字符串末尾的指针。

PathRemoveArgs 调用 PathGetArgs,然后使用返回的指针终止字符串。如果遇到的第一个空格恰好在行尾,它还会去除尾随空格。

CommandLineToArgvW 获取提供的字符串并将其拆分为一个数组。它使用空格来描述数组中的每个项目。数组中的第一项可以用引号引起来以允许有空格。第二个和后续项目也可以被引用,但它们支持稍微复杂的处理 - 参数也可以通过在它们前面加上反斜杠来包含嵌入的引号。例如:

 "c:\program files\my app\my app.exe" arg1 "argument 2" "arg \"number\" 3"

这将产生一个包含四个条目的数组:

  • argv[0] - c:\program files\my app\my app.exe
  • argv[1] - arg1
  • argv[2] - 参数 2
  • argv[3] - arg“数字”3

参见 CommandLineToArgVW有关解析规则的完整描述的文档,包括如何在参数中嵌入反斜杠和引号。

关于c++ - PathGetArgs/PathRemoveArgs 与 CommandLineToArgvW - 有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20103638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com