如何使用 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]....
最佳答案
从外观上看,您错误地形成了 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 包含的内容?我想如果您有的话,您会很快发现问题。
希望对您有所帮助!
关于c++ - 如何使用 SHFILEOPSTRUCT 移动多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1259432/