首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

SHFileOperation 这个API函数如何用起来结果飘忽不定

2014-01-12 
SHFileOperation 这个API函数怎么用起来结果飘忽不定?环境:vs2005.我的一个复制文件夹的函数如下:// 将原

SHFileOperation 这个API函数怎么用起来结果飘忽不定?
环境:vs2005.我的一个复制文件夹的函数如下:

// 将原路径srcDir中的文件/文件夹(不包括srcDir本身),拷贝到目标路径desDir下,存在的话覆盖
bool copyForder(const char * srcDir,const char *desDir)
{
SHFILEOPSTRUCT fop; 
ZeroMemory(&fop, sizeof(fop)); 
fop.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR |FOF_MULTIDESTFILES; 
fop.wFunc = FO_COPY; 
fop.pFrom = _T(srcDir); 
fop.pTo = _T(desDir); 

int nResult = SHFileOperation(&fop);
if(0 == nResult) 
{
return true;
}

return false;
}

测试代码如下:
string src="D:\\source\";
string des = "D:\\dest\\aaa\";
if(!copyForder(src.c_str() ,des.c_str()))
printf("文件夹拷贝失败!\n");
else
printf("文件夹拷贝成功!\n");
好像文件夹路径最后加不加那个斜杠会影响结果?之前试的时候从source往dest中复制的话怎么折腾都成功,现在往dest下的aaa文件夹里放感觉有时候就会失败,nResult返回值有时候是123,有时候是87,有墙,还查不到更多的信息,有时候复制成功但是又吧source本身都复制过去了,好混乱啊,到底怎么正确使用呢?
[解决办法]
http://msdn.microsoft.com/en-us/library/windows/desktop/bb775771(v=vs.85).aspx
微软更推荐用IFileOperation
[解决办法]
Important  You must ensure that the source and destination paths are double-null terminated. A normal string ends in just a single null character. If you pass that value in either the source or destination members, the function will not realize when it has reached the end of the string and will continue to read on in memory until it comes to a random double null value. This can at least lead to a buffer overrun, and possibly the unintended deletion of unrelated data.

如果非要说LZ有啥问题,你的源路径和目标路径都必须是双null结尾,因为这个API支持多个路径放一起,用null隔开,所以双null才是标志路径结束。
example

// WRONG
LPTSTR pszSource = L"C:\\Windows\\*";

// RIGHT
LPTSTR pszSource = L"C:\\Windows\\*\0";

[解决办法]
引用:
Quote: 引用:

http://msdn.microsoft.com/en-us/library/windows/desktop/bb775771(v=vs.85).aspx
微软更推荐用IFileOperation
怎么用啊?比较紧急啊,没有多少时间来自己研究了,或者有其他好用的赋值文件夹的代码也可以。xcopy命令行的就算了,现有的就是这个,用其他的来替换的。


我刚刚又看了下IFileOperation要求windows最低版本wista,实在有点坑,LZ,你试试我说的在字符串结尾在加个"\0"吧,这是msdn说滴
其实copy文件,boost提供了一个跨平台的支持,就是FileSystem库,不过这个库是需要编译的。用法和Java里的File类很像,并且提供文件拷贝,复制,删除等等操作~
[解决办法]
引用:
Quote: 引用:

Important  You must ensure that the source and destination paths are double-null terminated. A normal string ends in just a single null character. If you pass that value in either the source or destination members, the function will not realize when it has reached the end of the string and will continue to read on in memory until it comes to a random double null value. This can at least lead to a buffer overrun, and possibly the unintended deletion of unrelated data.

如果非要说LZ有啥问题,你的源路径和目标路径都必须是双null结尾,因为这个API支持多个路径放一起,用null隔开,所以双null才是标志路径结束。
example

// WRONG
LPTSTR pszSource = L"C:\\Windows\\*";

// RIGHT
LPTSTR pszSource = L"C:\\Windows\\*\0";
我看过网上说的,末尾也加上"\0\0"了,还是不稳定

应该是多一个"\0",因为字符串本身就有一个"\0",不过感觉这貌似不是问题,LZ可以试试把FOF_NOERRORUI这个flag去掉,看看错误到底是啥~
还有我上面给的示例代码就是msdn提供的,或许它就是不支持末尾是"\"的,你干脆再弄个函数,一旦末尾源路径末尾是"\",你就改成"\\*\0",这应该不难吧~

热点排行