SHFILEOPSTRUCT不确定如何加倍转义字符串

时间:2015-10-15 10:56:50

标签: c++ codeblocks

我正在尝试将正在运行的可执行文件复制到特定文件夹。我想用相同的安全资源属性复制它。但是,我不确定我是不是"双重逃避"文件名正确,如本doc

中所述

我的代码如下:

#include <shlobj.h>
#include <shellapi.h>

#define LIVE_FOLDER "Cloud9"

bool CopySelf()
{
  TCHAR buf[MAX_PATH];
  TCHAR path[MAX_PATH];
  TCHAR ogpath[MAX_PATH];
  // The function gets the current module for you.
  SHGetFolderPath(NULL,CSIDL_APPDATA, NULL, 0, path);


  GetCurrentDirectory(MAX_PATH, ogpath);
  std::string dir =  std::string(path)+"\\"+LIVE_FOLDER ;
  std::string dirog = std::string(ogpath);

  if(dir==dirog)
  {
    return false;
  }
  if (CreateDirectory(dir.c_str(), NULL) ||
        ERROR_ALREADY_EXISTS == GetLastError())
  {
        std::string newprocessName = dir + "\\test.exe\0\0";

        GetModuleFileName(0, buf, MAX_PATH);
        std::string oldprocessName = std::string(buf)+"\0\0";

        SHFILEOPSTRUCT a=
        {
            NULL,
            FO_COPY,
            oldprocessName.c_str(),
            newprocessName.c_str(),
            FOF_SILENT|FOF_NOERRORUI|FOF_NOCONFIRMATION,
            FALSE,
            NULL,
            NULL,
        };



        SHFileOperation(&a);

        return true;
  }
  else
  {
      throw ERROR;
   // return false;
  }
  return false;
}

当我运行此代码而不是目的地的可执行文件时,会有一个名为&#34; test.exe&#34;。Image is here - not enough points to embed it.

的文件夹

如果我使用带有以下代码的CopyFile或CopyFileEx,则会正确复制文件。

std::string newprocessName = dir + "\\test.exe";
GetModuleFileName(0, buf, MAX_PATH);
CopyFile(buf, newprocessName.c_str(), TRUE);

这样做的问题是不会复制安全属性。在这一点上,我不确定我是否失败了&#34;双重逃避&#34; /&#34;双重终止&#34;或者我做错了什么。为什么要创建一个名为&#34; test.exe&#34;的文件夹。而不是复制文件?

我正在使用Code :: Blocks with GCC编译器,我在Windows 8.1 Professional和Windows 7 Professional上试过这个。

1 个答案:

答案 0 :(得分:1)

终于明白了。问题确实是双重空终止

我使用append附加了一个null终止符,如下所示,并在声明字符串时使用单个null终止符:

std::string newprocessName = dir + "\\test.exe\0";
GetModuleFileName(0, buf, MAX_PATH);
std::string oldprocessName = std::string(buf)+"\0";
newprocessName.append(1, '\0');
oldprocessName.append(1, '\0');

不确定这有什么不同,但它现在正在发挥作用。 this SO page上接受的答案正是我所需要的。