views:

182

answers:

1

How to move multi files using SHFILEOPSTRUCT?

            vector<CString> srcPaths;
            vector<CString> dstPaths;
 SHFILEOPSTRUCT FileOp;//定义SHFILEOPSTRUCT结构对象;
 int fromBufLength = MAX_PATH * imageVec.size() + 10;

 TCHAR *FromBuf = new TCHAR[fromBufLength];
 TCHAR *ToBuf = new TCHAR[fromBufLength];

 shared_array<TCHAR> arrayPtr(FromBuf);
 shared_array<TCHAR> arrayPtr2(ToBuf);
 ZeroMemory(FromBuf, sizeof(TCHAR) * fromBufLength);
 ZeroMemory(ToBuf, sizeof(TCHAR) * fromBufLength);

 // 拼接移动自目录字符串
 int location = 0;
 TCHAR* tempBuf = FromBuf;
 for (int i = 0; i < srcPaths.size(); ++i)
 {
  const CString& filePath = srcPaths[i];
  if (i != 0)
  {
   location ++;
  }
  tempBuf = FromBuf + location;
  wcsncpy(tempBuf, (LPCTSTR)(filePath), filePath.GetLength());
  location += filePath.GetLength();
 }
 // 拼接移动到目录字符串
 location = 0;
 tempBuf = ToBuf;
 CString filePath;
 for (int i = 0; i < dstPaths.size(); ++i)
 {
  filePath = dstPaths[i];
  if (i != 0)
  {
   location ++;
  }
  tempBuf = ToBuf + location;
  wcsncpy(tempBuf, (LPCTSTR)(filePath), filePath.GetLength());
  location += filePath.GetLength();
 }
 tempBuf = NULL;

 FileOp.hwnd = NULL/*this->m_hWnd*/;
 FileOp.wFunc=FO_MOVE;
 FileOp.pFrom = FromBuf;
 FileOp.pTo = ToBuf;
 FileOp.fFlags = FOF_NOCONFIRMATION;
 FileOp.hNameMappings = NULL;
 int nOk=SHFileOperation(&FileOp);

Is there anything wrong? It always say no XXX directory. XXX the dstPaths[0]....

+1  A: 

By the look of it you are forming your pFrom and pTo lists wrongly.

You need to form them such that each has a NULL terminator between them and a double null terminator at the end.

An example re-implementation of your function would be:

TCHAR* tempBuf = FromBuf;
for (int i = 0; i < srcPaths.size(); ++i)
{
        const CString& filePath = srcPaths[i];
        _tcscpy_s( tempBuf, fromBufLength, filePath.GetString() ); 
        tempBuf += filePath.GetString() + 1; // Include null terminator in the increment.
}
*tempBuf = '\0'; // Add extra null terminator.

The main problems in your original code is that you are not payign attention to the required null terminators between each file name. Have you tried running what you have through the debugger and looking at what FromBuf contains? I suspect you would have seen the problem very quickly if you had.

Hope that helps!

Goz