c++ - 如何使用 SHFILEOPSTRUCT 移动多个文件?

标签 c++ windows filesystems

如何使用 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/

相关文章:

c++ - C++ 中的 "free(): invalid next size (fast)"

c++ - 在 union 中存储 STL 迭代器是否合法?

c++ - QIODevice::writeData 麦克风

python - 如何在 win 7 64 上安装 libxml2 2.9.0 for lxml for Python 3.4.3?

Java 音频流平台独立

linux - 拦截读取特定文件的请求,并生成以编程方式读取的该文件的明显输出

architecture - 用于存储视频数据的关系数据库

c++ - 如何创建一个从 0 到用户输入的数组

c# - Windows Azure 持久存储技巧

java - 每 x 秒读取新文件夹并使用其数据