为什么通过swprintf_s拼接的路径无法用SHFileOperation删除文件?-灵析社区

万码JFG3236P

如题,代码如下: ```c++ WCHAR szPath[MAX_PATH] { L'\0' }; swprintf_s(szPath, MAX_PATH, L"%ls\\abc.txt\0", L"D:"); BOOL ret = PathFileExistsW(szPath); wprintf(L"%ls exists: %d\n", szPath, ret); SHFILEOPSTRUCT fileOp; fileOp.wFunc = FO_DELETE; fileOp.pFrom = szPath; fileOp.fFlags = FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI; DWORD dwError = SHFileOperationW(&fileOp); wprintf(L"%ls delete ret: 0x%08X\n", szPath, dwError); ``` 上述代码输出结果为: ![https://wmprod.oss-cn-shanghai.aliyuncs.com/community/1724813521743_TbEa.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/community/1724813521743_TbEa.png) 只有手写路径才能删除成功,如fileOp.pFrom = L"D:\abc.txt\0" 通过swprintf_s拼接的路径字符串则失败

阅读量:208

点赞量:0

问AI
SHFILEOPSTRUCTW (shellapi.h) - Win32 apps | Microsoft Learn 微软官方文档要求SHFILEOPSTRUCT的pFrom字段要以双null结尾: "https://wmprod.oss-cn-shanghai.aliyuncs.com/community/1724825182486_fVUG.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/community/1724825182486_fVUG.png) 因此只需要在字符串结尾再补一个null即可,修改的代码如下: int len = swprintf_s(szPath, MAX_PATH, L"%ls\\abc.txt", L"D:"); szPath[len + 1] = L'\0'; BOOL ret = PathFileExistsW(szPath); wprintf(L"%ls exists: %d\n", szPath, ret); SHFILEOPSTRUCT fileOp; fileOp.wFunc = FO_DELETE; fileOp.pFrom = szPath; fileOp.fFlags = FOF_NOCONFIRMATION | FOF_SILENT | FOF_NOERRORUI; DWORD dwError = SHFileOperationW(&fileOp); wprintf(L"%ls delete ret: 0x%08X\n", szPath, dwError); 最终结果: "https://wmprod.oss-cn-shanghai.aliyuncs.com/community/1724825274079_iLo5.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/community/1724825274079_iLo5.png)