c++ - 将 %APPDATA% 与 CreateProcessW 一起使用

标签 c++ windows winapi createprocess

我有一个简单的代码,它使用 system() 通过变量 %APPDATA% 将文件下载到 AppData,我想使用 CreateProcessW 而不是系统,但出于某种原因,当我在 CreatProcess 下使用相同的命令时,它会查找"Working Dir"\%APPDATA% 而不是实际的 AppData 目录,并引发异常。

System() 工作代码:

system("powershell.exe -command Invoke-WebRequest https://the.earth.li/~sgtatham/putty/latest/w32/putty.exe -OutFile '%APPDATA%\\putty.exe'");

CreateProcessW代码:

wchar_t cmdArgs[] = L"powershell.exe -command Invoke-WebRequest https://the.earth.li/~sgtatham/putty/latest/w32/putty.exe -OutFile '%APPDATA%\\putty.exe'";
CreateProcessW(NULL, cmdArgs, nullptr, nullptr, false, 0, nullptr, nullptr, &si, &pi)

异常:

Invoke-WebRequest : Could not find a part of the path 'G:\Projects\C++\PS_Tries\PS_Tries\%APPDATA%\putty.exe'.
At line:1 char:1
+ Invoke-WebRequest https://the.earth.li/~sgtatham/putty/latest/w32/put ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Invoke-WebRequest], DirectoryNotFoundException
    + FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

如何让它像 system() 那样扩展 %APPDATA%?

最佳答案

您可以使用 _wdupenv_s获取 appdata 路径的函数,然后将其与您的参数 concatenate

wchar_t *w_app_data_path;
size_t sz = 0;
errno_t err = _wdupenv_s(&w_app_data_path, &sz, L"APPDATA");
wchar_t cmdArgs[2048]{ 0 };
wsprintfW(cmdArgs, L"powershell.exe -command Invoke-WebRequest https://the.earth.li/~sgtatham/putty/latest/w32/putty.exe -OutFile '%s\\putty.exe'", w_app_data_path);
free(w_app_data_path);
CreateProcessW(NULL, cmdArgs, nullptr, nullptr, false, 0, nullptr, nullptr, &si, &pi)

关于c++ - 将 %APPDATA% 与 CreateProcessW 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53740716/

相关文章:

c++ - 将 LPSTR 转换为 LPCTSTR

c++ - Visual Studio 2013 : error C2039: 'SetDefaultDllDirectories' : is not a member of '` global namespace''

python - OpenCV - 从 C++ 到 Python 打开一个 XML 文件

c++ - 为什么 std::tie 不能与 const 类方法一起使用?

windows - 调试启动后终止的进程

c++ - MFC CDialog::Create 在 x64 上挂起

c++ - 如何用 Python 判断一个文件在 Windows 上是否可执行?

c++ - 如何在 Windows 上使用和配置 clang-tidy?

c++ - 函数中有函数原型(prototype)的目的是什么?

python - cx_Freeze 和 seaborn - ImportError : No module named 'scipy.spatial.ckdtree'