如何使用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);
有什么不对吗? 它总是说没有XXX目录。 XXX dstPaths [0] ....
答案 0 :(得分:1)
从表面上看,你正在错误地形成你的pFrom和pTo列表。
你需要构造它们,使它们之间有一个NULL终止符,并在末尾有一个双空终止符。
您的函数重新实现的示例如下:
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.
原始代码中的主要问题是您没有注意每个文件名之间所需的空终止符。您是否尝试通过调试器运行所有内容并查看FromBuf包含的内容?如果你有的话,我怀疑你会很快看到这个问题。
希望有所帮助!