简体   繁体   English

是否有WinAPI可以从命令行获取带有可选空格和其他参数的文件名?

[英]Is there a WinAPI to get filename from a command line with optional spaces and other parameters?

My goal is get a file name from a command line call/string. 我的目标是从命令行调用/字符串获取文件名。 For instance, if I have the following strings on the input: 例如,如果我在输入中包含以下字符串:

C:\WINDOWS\system32\mstsc.exe /v:%WKSNAME% /f
"C:\Users\User Name\Desktop\My Program.exe" /?

The API should return the following respectively: API应该分别返回以下内容:

mstsc.exe
My Program.exe

So I tried to use splitpath function, and although it works for a very simple file path, it totally fails on my two examples above. 因此,我尝试使用splitpath函数,尽管它适用于非常简单的文件路径,但是在上面的两个示例中它完全失败了。

I understand that I can write my own parser (so please don't offer that.) I'm curious if there's a built-in Windows API that does it already? 我知道我可以编写自己的解析器(因此请不要提供该解析器。)我很好奇是否已经有内置的Windows API吗?

PS. PS。 There must be one that OS uses internally to parse those. OS必须在内部使用一种解析它们。

PS2. PS2。 Here's the code I've been toying with: 这是我一直在玩的代码:

TCHAR buffFileName[MAX_PATH];
TCHAR buffExt[MAX_PATH];

LPCTSTR strInputPath = L"C:\\WINDOWS\\system32\\mstsc.exe /v:%WKSNAME% /f";
if(_tsplitpath_s(strInputPath, NULL, 0, NULL, 0, buffFileName, MAX_PATH, buffExt, MAX_PATH) == 0)
{
    //Got something
}

I believe PathFindFileName may be what you're looking for. 我相信PathFindFileName可能就是您想要的。 From the docs: 从文档:

Searches a path for a file name. 在路径中搜索文件名。

The examples within the docs seem to show the exact behavior you describe. 文档中的示例似乎显示了您描述的确切行为。


If you'd rather parse the entire command-line, CommandLineToArgvW may be helpful. 如果您想解析整个命令行,则CommandLineToArgvW可能会有所帮助。 It takes a command-line and splits it into an array containing the filename and any arguments. 它使用命令行并将其拆分为包含文件名和所有参数的数组。

This function's parsing rules are fairly intricate, so be sure to look over the docs, but a simple explanation of them can be found in this answer . 该函数的解析规则相当复杂,因此请务必查看文档,但是可以在此答案中找到对它们的简单说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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