gpt4 book ai didi

c++ - 无法格式化 PWSTR 变量中的数据以在 CopyFileW 命令中使用

转载 作者:行者123 更新时间:2023-11-28 06:43:15 25 4
gpt4 key购买 nike

我对此很陌生,对于下面的可怕代码感到抱歉。我正在尝试获取 FOLDERID_Profile 的默认路径,然后将“\test.exe”添加到它的末尾。然后我需要使用它作为将文件复制到的路径。我能够使用 pSHGetKnownFolderPath 方法将配置文件目录存储在 PWSTR user_dir 中。问题是,这不是复制函数可接受的字符串格式。

所以我使用以下代码非常粗暴地尝试将其转换为复制函数可以使用的内容。

            strcat((char *)user_dir,"\\test.exe");
test7 = (LPCWSTR)user_dir;
MessageBox(NULL,test7,L"WR test file",MB_OK);

我在使用 CopyFile(currentpath,test7,false) 之前使用消息框检查路径;但这让我感到㩃瑜獥⹴硥。我目前正在使用

            CopyFileW(currentpath,L"C:\\Users\\Jenia\\test.exe",false);

作为解决方法,但我真的需要它在其他计算机上也能工作...

我知道我又搞砸了我的 ANSI 和 Unicode 格式,请告诉我如何最好地实现这个目标。让我知道您是否希望我发布整个代码块,但在我运行该 strcat 方法之前,user_dir 具有正确的路径,只是没有用于复制方法的文件名。

下面是更完整的代码:

        #include <windows.h>
#include <shlwapi.h>
#include <stdio.h>
#include <Shlobj.h>

LPCWSTR test7 = 0;
PWSTR user_dir = 0;

HMODULE hndl_shell32;
lpSHGetKnownFolderPath pSHGetKnownFolderPath;

hndl_shell32 = LoadLibrary(L"shell32");
if (NULL != hndl_shell32)
{
pSHGetKnownFolderPath = (lpSHGetKnownFolderPath)
GetProcAddress(hndl_shell32, "SHGetKnownFolderPath");

if(pSHGetKnownFolderPath != NULL)
{

if (SUCCEEDED(pSHGetKnownFolderPath(
FOLDERID_Profile,
0,
NULL,
&user_dir)))
{
//I think this is the problem here
strcat((char *)user_dir,"\\test.exe");
test7 = (LPCWSTR)user_dir;
MessageBox(NULL,test7,L"WR test file",MB_OK);
}
}
else
{
fprintf(stderr, "Failed to locate function: %d\n",
GetLastError());
}

}
else
{
fprintf(stderr, "Failed to load shell32.dll: %d\n", GetLastError());
}

最佳答案

此处错误太多。您不能在由 SHGetKnownFolderPath 填充的指针上 strcat。假设所有变量都是 Unicode,这应该适用于任何字符集的项目:

LPWSTR test7 = 0;
WCHAR user_dir[MAX_PATH];
...
SHGetKnownFolderPath(... &test7);
...
wcscpy(user_dir, test7);
wcscat(user_dir, L"\\test.exe");
MessageBoxW(NULL,test7,L"WR test file",MB_OK);

不要忘记释放由SHGetKnownFolderPath 填充的指针test7

关于c++ - 无法格式化 PWSTR 变量中的数据以在 CopyFileW 命令中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25519800/

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